简体   繁体   中英

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?

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

去抖动时间与节流时间与审计时间与采样时间

Hope this helps

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM