Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine interval stream with Promise stream in RxJs and get the values?

I'm learning RxJs and it's pretty cool. I'm trying to create a page where the Ajax call is interval so the data will be refreshing every 5 seconds. So I thought I would be doing this.

var ajax = new Promise(function(resolve) {
  return resolve('test');
});

var source1 = Rx.Observable.interval(5000)
  .map(function(i) {
    return Rx.Observable.fromPromise(ajax);
  });

source1.subscribe(function(res) {
    res.subscribe(function(pro) {
    console.log(pro);
  })
});

However, the fact that I need to do two subscribes got me thinking that I might be doing something wrong here. I'm not sure if I'm going the right direction?

What I want is a stream of promises that will be fetched every 5 seconds.

Here's my jsfiddle

https://jsfiddle.net/noppanit/2y179dgg/

like image 348
toy Avatar asked Nov 18 '25 11:11

toy


1 Answers

You need to use flatMap operator. Have a look at the jsbin here.

var ajax = new Promise(function(resolve) {
  return resolve('test');
});

var source1 = Rx.Observable.interval(1000)
  .flatMap(function(i) {
    return Rx.Observable.fromPromise(ajax);
  });

source1.subscribe(function(res) {
    console.log(res);
});

There are extensive examples of use of flatMap available on SO.

You can also consult:

  • From SO : Why we need to use flatMap?
  • the nicely presented : The introduction to Reactive Programming you've been missing
  • Official doc : https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/selectmany.md
  • Illustrative marbles : http://reactivex.io/documentation/operators/flatmap.html
like image 115
user3743222 Avatar answered Nov 20 '25 05:11

user3743222