码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2016-03-09 06:56:33      阅读:185      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!