Stas.dp
Stas.dp

Reputation: 127

BehaviorSubject subscription with debounce

I have BehaviorSubject property

public results$ = new BehaviorSubject(null);

Lets'say I have a subscription to this

this.results$.subscribe(() => this.find());

Subscription in being invoked each time when I press any key on keyboards inside input element. So, to prevent many requests to the server, I added debounceTime()

this.results$
   .pipe(debounceTime(500))
   .subscribe(() => this.find());

But I need to invoke the first this.find() without any debounce, just immediately.

How can I do that?

Upvotes: 3

Views: 2459

Answers (1)

Jasdeep Singh
Jasdeep Singh

Reputation: 8301

I would suggest you to use throttleTime instead of debounceTime. It propagates the first value and then wait for the specified amount of time.

Also change the BehaviorSubject to Subject.

public results$ = new Subject();

this.results$
   .pipe(
         filter(value => !!value && value.length >= 3),
         throttleTime(500))
   .subscribe(() => this.find());

Please read about throttleTime, auditTime and debounceTime here - https://rxjs-dev.firebaseapp.com/guide/operators

Upvotes: 4

Related Questions