Search code examples
angularrxjsangular2-observables

How can I use multiple debounceTime on one Observable?


I have an input html element and doing a basic type ahead search function using Observables:

The code:

   @Output() keywordChange = new EventEmitter();

   this.keyword$ = Observable.fromEvent(myInput, 'keyup');
    this.keyword$
      .map((event: any) => event.target.value)
      .debounceTime(200)
      .subscribe(keyword => this.keywordChange.emit(keyword));

So basically I'm capturing any keywords typed with at at least 200 ms between each keyup.

Now I want to save whatever the user is searching for in a cookie, in order to show them "Your latest searches" but I want to wait 3000 ms before saving the values typed.

I know the following code won't work but just to illustrate, I want to achieve something similiar to this:

    this.keyword$
      .map((event: any) => event.target.value)
      .debounceTime(200)
      .subscribe(keyword => this.keywordChange.emit(keyword))
      .debounceTime(3000)
      .subscribe(keyword => addKeyWordToLatestSearches(keyword));

Is this possible somehow, chaining operators to do multiple things with different debounceTimes?


Solution

  • Do you probably want to share the initial subscription to have the possibility of processing the emitted data in two independent ways? As you don't want to subscribe twice on the original source, you could use the share operator of RxJS.

    const keyupValue$ = this.keyword$
      .map((event: any) => event.target.value)
      .share();
    
    keyupValue$
      .debounceTime(200)
      .subscribe(keyword => this.keywordChange.emit(keyword))
    
    keyupValue$ 
      .debounceTime(3000)
      .subscribe(keyword => addKeyWordToLatestSearches(keyword));