Is it possible to have a debounceTime value set to something that changes based on a condition? I have a behavior subject setup as so (and please tell me if I'm doing even this part wrong):
this.searchSubject.asObservable().debounceTime(1000).subscribe(x => this.emitFilters())
I'd like the debounce time to be different based on certain filter conditions, but when I try to throw a function in there, VS Code complains that it's not valid.
I also took a look at debounce, which seems to take a type of variable, but from the documentation, I can't seem to figure it out (the function I threw in returned the wrong type according to VS Code, even though I copied from documented code). I'm doing all this in Angular 2 if it makes a difference.
Where did you see documentation that suggested that .debounceTime would accept a function? It is well documented here with the following signature:
public debounceTime(dueTime: number, scheduler: Scheduler): Observable
The method you're looking for is debounce which, according to the documentation:
Emits a value from the source Observable only after a particular time span determined by another Observable has passed without another source emission.
It's like debounceTime, but the time span of emission silence is determined by a second Observable.
Here is it's signature:
public debounce(durationSelector: function(value: T): Observable | Promise): Observable
So, all you have to do to accomplish the behavior you're after is to set up another Observable which will provide the interval at which to debounce.
You could do this using another Subject which you could call .next() on according to application logic to provide the new wait period.
let debounceSubject = new Subject<number>();
let debounceObservable$ = debounceSubject.asObservable();
// Somewhere else in code you'll do debounceSubject.next(1000); for example
And finally you would set up your new debounce like this:
this.searchSubject.asObservable()
.debounce(() => debounceObservable$).subscribe(x => this.emitFilters())
More examples of using .debounce can be found here (great website for learning rxjs) including working examples with jsBin and jsFiddle.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With