简体   繁体   中英

Throttling requests with RxJS's switchMap

I'm looking for a way to leverage RxJS 5 to handle requests fired in arbitrary time and emit only the latest result.

I'm trying to tackle this problem with Subject and switchMap . Ideally I would like to observe string values (urls) and emit a response. If new url is observed before any previous response is received it should be forgotten (or cancelled - I believe this one is actually implemented in switchMap ).

I've managed to produce following code:

const stream$ = new Rx.Subject()
  .switchMap(url => Rx.Observable.fromPromise(
    fetch(url).then(res => res.json())
  ))
  .subscribe(res => console.log(res));

stream$.next('https://some-api-server.com/1');
stream$.next('https://some-api-server.com/2');
stream$.next('https://some-api-server.com/3');

From what I understand of switchMap the console output should only show the result of last request. Instead it shows the urls I passed to the stream$ . What I'm getting wrong?

Your code can be rewritten as following:

const subject = new Rx.Subject();
const stream$ = subject
  .switchMap(url => Rx.Observable.fromPromise(
    fetch(url).then(res => res.json())
  ));


const subscription = stream$.subscribe(res => console.log(res));

subscription.next('https://some-api-server.com/1');
subscription.next('https://some-api-server.com/2');
subscription.next('https://some-api-server.com/3');

And, as you can see, you are pushing urls into subscription, but not into subject… Not sure why it has next method, maybe it is implementation details.

To make it working properly - push urls into subject variable

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