user8360241
user8360241

Reputation:

Setting up throttleTime() operator correctly

I have a button whose click event handler is set to a function: <button (click)="someFunction(test1)">get stuff</button>

someFunction() does some stuff but then it calls a service function that does a http get.

 this._myService.getDetails(username).pipe(
      throttleTime(10000)
).subscribe()

In my service:

  getDetails(username: string) {
    return this._http.get(url);
  }

This obviously won't work because every time I click the button a new http get call is issued.

What would be a good way of setting up a throttleTime()-like functionality where http get calls are issued after a certain time out length?

Upvotes: 1

Views: 1829

Answers (2)

kos
kos

Reputation: 5384

You do need a throttleTime (see the comparative marble diagram below)

Yet currently you're throttling the response stream, instead you need to throttle your button click stream.

To do so, we can create a stream out of button clicks:

<button (click)="someFunction(test1)">get stuff</button>
class Component {
  btnClickSubject$ = new Subject<void>();
  someFunction(){
    this.btnClickSubject$.next(void 0);
  }
}

And then *Map it to the http-get request:

class Component {
  //...

  destroy$ = new Subject<void>();

  ngOnInit() {
    this.btnClickSubject$.pipe(
      // throttle clicks
      throttleTime(3000),

      // switchMap or other *Map operator to switch to http-get
      switchMap(() => this._http.get('url')),

      // complete with component destroy *
      takeUntil(this.destroy$)
    )
    .subscribe(response => console.log(response))
  }


  ngOnDestroy() {
    this.destroy$.next(void 0);
  }

}

* Note that we need explicitly tell this subscription to complete with component "onDestroy"

--

And heres a comparison of debounceTime vs throttleTime vs auditTime vs sampleTime

debounceTime vs throttleTime vs auditTime vs sampleTime

Hope this helps

Upvotes: 2

bugs
bugs

Reputation: 15323

What you are looking for is the debounceTime operator.

debounceTime delays values emitted by the source Observable, but drops previous pending delayed emissions if a new value arrives on the source Observable. This operator keeps track of the most recent value from the source Observable, and emits that only when dueTime enough time has passed without any other value appearing on the source Observable. If a new value appears before dueTime silence occurs, the previous value will be dropped and will not be emitted on the output Observable.

See an example here.

The official RxJS docs are here.

Upvotes: 1

Related Questions