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

时间:2023-03-09 00:08:15
[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.