[RxJS] Reactive Programming - Sharing network requests with shareReplay()

Posted Answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[RxJS] Reactive Programming - Sharing network requests with shareReplay()相关的知识,希望对你有一定的参考价值。

Currently we show three users in the list, it actually do three time network request, we can verfiy this by console out each network request:

var responseStream = startupRequestStream.merge(requestOnRefreshStream)
  .flatMap(requestUrl => {
    console.log(‘do network request‘);
    return Rx.Observable.fromPromise(jQuery.getJSON(requestUrl));
  });

 

We actually can use the same network request by shareReplay(1):

var responseStream = startupRequestStream.merge(requestOnRefreshStream)
  .flatMap(requestUrl => {
    console.log(‘do network request‘);
    return Rx.Observable.fromPromise(jQuery.getJSON(requestUrl));
  })
  .shareReplay(1);

 

Why replay one? Well, that‘s because if there happens to be a really late subscriber...let‘s say someone does a setTimeout and doesn‘t subscribe to the responseStream after a long while. Let‘s say, three seconds or even 10 seconds. Then, this subscribe will get a replayed response JSON. It will not do a new network request, but it will simply replay that same JSON that happened before.

以上是关于[RxJS] Reactive Programming - Sharing network requests with shareReplay()的主要内容,如果未能解决你的问题,请参考以下文章

[RxJS] Reactive Programming - Using cached network data with RxJS -- withLatestFrom()

[RxJS] Reactive Programming - Sharing network requests with shareReplay()

[RxJS] Reactive Programming - New requests from refresh clicks -- merge()

Reactive-Extensions / RxJS和ReactiveX / rxjs之间有什么区别

全面拥抱 Reactivity: RxJS, RSocket & Svelte

RxJS的基础