Rxjs - API request output and retry when cache is empty

I am trying to implement a version of this introduction to RxJS ( fiddle here ) that instead of selecting a random object from the returned API array, it consumes a reverse stream of objects from the returned API array.

Here is the part of the code that creates the managed ObservableAPI response (full script here ):

var responseStream = requestStream.flatMap(function (requestUrl) {
    return Rx.Observable.fromPromise(fetch(requestUrl));
}).flatMap(function(response) {
    return Rx.Observable.fromPromise(response.json());
}).flatMap(function(json) {
    return Rx.Observable.from(json);
}).controlled();

I simply delete each emitted user in console.logand use the event stream clickto trigger the call request()in a controlled Observable:

responseStream.subscribe(function(user) {
  console.log(user);
});

refreshClickStream.subscribe(function (res) {
    responseStream.request(1);
});

50 , API GitHub, ( ). , , requestStream, API, responseStream console.log . RxJS- ?

+1
1

combineLatest(), , , .

3- . 3- , . , , Subject , .

, concatMap(), . , , combineLatest(), .

-: https://jsfiddle.net/h3bwwjaz/12/

var refreshButton = document.querySelector('#main');
var refreshClickStream = Rx.Observable.fromEvent(refreshButton, 'click')
  .startWith(0)
  .scan(function(acc, val, index) {
    return index;
  });

var usersStream = refreshClickStream
  .filter(function(index) {
    return index % 3 === 0;
  })
  .concatMap(function() {
    var randomOffset = Math.floor(Math.random() * 500);
    var url = 'https://api.github.com/users?since=' + randomOffset + '&per_page=3';
    return Rx.Observable.fromPromise(fetch(url))
      .flatMap(function(response) {
        return Rx.Observable.fromPromise(response.json());
      });
  })
  .combineLatest(refreshClickStream, function(responseArray, index) {
    return responseArray[index % 3];
  })
  .distinct();

usersStream.subscribe(function(user) {
  console.log(user);
});

refreshClickStream :

  • combineLatest()
  • , , ( filter()).

distinct() , , index % 3 === 0, . -, , , - combineLatest(), , . distinct() .

distinct(), .

+2

Source: https://habr.com/ru/post/1690281/


All Articles