简体   繁体   中英

Rxjs: Poll data until predicate is met

import {Observable} from '@reactivex/rxjs'

// This is a fake API polling, this data is in reality coming from
// the server
const fakePoll$ = Observable.from([
  {
    status: 'initialized',
    data: {...},
  },
  {
    status: 'progress',
    data: {...},
  },
  {
    status: 'progress',
    data: {...},
  },
  {
    status: 'progress',
    data: {...},
  },
  {
    status: 'completed',
    data: {...},
  },
  ...
  {
    status: 'completed',
    data: {...},
  },
])

fakePoll$
  .takeWhile(x => x.status != 'completed')
  .subscribe(x => console.log(x))

This snippet returns all the progress and initialized statuses:

initialized
progress
progress
progress

But I need to get the first completed also like a takeWhile but inclusive.

You could consider adding it back like here, if that is all you need :

Rx.Observable.concat(fakePoll$
  .takeWhile(x => x != 'completed'), Rx.Observable.from('completed'))
  .subscribe(x => console.log(x))

I believe you have to use repeat when using an api assuming it is a promise returning call. I did this as in
Server Polling // Code goes here

angular.module('rxApp', ['rx'])
  .controller('AppCtrl', function($scope, $http, rx) {
    function getRandom(){
       return Math.floor(Math.random() * (10 - 1)) + 1;
    }

    function getResults(){
       console.log("returning promise");
       return $http({
          url: "https://en.wikipedia.org/w/api.php?&callback=JSON_CALLBACK",
          method: "jsonp",
          params: {
            action: "opensearch",
            search: 'eclipse',
            format: "json"
          }
        });
    }
    var toBeRepeated =  rx.Observable
    .fromPromise(getResults).repeat()
    .map(response => { console.log(response); return response.data[1]; })
    .map(results => {
        var rs = results[getRandom()];
        console.log(rs);
        return rs;
    });             

    var source = toBeRepeated.takeWhile(rs => rs.indexOf('play') === -1);
        source.subscribe(function(item){
        console.log("item:"+ item);
    },err => { console.log(err); },completed => {console.log("completed :" + completed);} );
});

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM