您的位置:首页 > Web前端 > React

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

2016-03-09 03:31 591 查看
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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: