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

Now we want each time we click refresh button, we will get new group of users. So we need to get the refresh button click event stream:

var refreshButton = document.querySelector('.refresh');
var refreshClickStream = Rx.Observable.fromEvent(refreshButton, 'click');

 

Then each time refreshClickStream happens, we will get users request url:

var requestOnRefreshStream = refreshClickStream
  .map(ev => {
    var randomOffset = Math.floor(Math.random()*500);
    return 'https://api.github.com/users?since=' + randomOffset;
  });

 

And we use this url to get json object:

var responseStream = requestOnRefreshStream
  .flatMap(requestUrl =>
    Rx.Observable.fromPromise(jQuery.getJSON(requestUrl))
  );

 

 

But the problem here is when the page loaded, we haven't click refresh button yet, therefore there is no data fetched fromt the server.

So we need to have a stream when the page loaded:

var startupRequestStream = Rx.Observable.just('https://api.github.com/users');

 

Then we can merge startUpRequestStream with requestOnRefreshStream:

var responseStream = requestOnRefreshStream
  .merge(startupRequestStream)
  .flatMap(requestUrl =>
    Rx.Observable.fromPromise(jQuery.getJSON(requestUrl))
  );

 

//-------a-----b-----c--------->
//s----------------------------->
//merge
//s------a-----b-----c--------->

 

posted @ 2016-03-08 19:31  Zhentiw  阅读(242)  评论(0编辑  收藏  举报