3

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/

toy
  • 11,711
  • 24
  • 93
  • 176

1 Answers1

9

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:

Community
  • 1
  • 1
user3743222
  • 18,345
  • 5
  • 69
  • 75
  • if you want to save your ordering of promises you can use `concatMap` instead of `flatMap` But more better for promises to use `flatMapLatest` – xgrommx Apr 08 '16 at 13:04
  • if you replace 'test' by a random string like Math.random().toString(36).substr(2, 5), you can see that the output variable doesn't change. Is there a way to force Promise to be executed at each interval? – khamaileon Mar 08 '17 at 14:37
  • promise are only ever resolved once so yeah that is the expected behavior. If at every interval you want a different promise, then do just that. `var source1 = Rx.Observable.interval(1000) .flatMap(function(i) { return makeYourPromiseHere(i); });` – user3743222 Mar 08 '17 at 15:37
  • Thx Captain Obvious! :) – khamaileon Mar 08 '17 at 16:07