首页 > Web开发 > 详细

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

时间:2016-03-09 06:53:34      阅读:161      评论:0      收藏:0      [点我收藏+]

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()

原文:http://www.cnblogs.com/Answer1215/p/5256574.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!