[RxJS] Reactive Programming - New requests from refresh clicks -- merge()
Posted Answer1215
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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--------->
以上是关于[RxJS] Reactive Programming - New requests from refresh clicks -- merge()的主要内容,如果未能解决你的问题,请参考以下文章
[RxJS] Reactive Programming - Using cached network data with RxJS -- withLatestFrom()
[RxJS] Reactive Programming - Sharing network requests with shareReplay()
[RxJS] Reactive Programming - New requests from refresh clicks -- merge()
Reactive-Extensions / RxJS和ReactiveX / rxjs之间有什么区别