javascript - How to combine interval stream with Promise stream in RxJs and get the values? - Stack Overflow

I'm learning RxJs and it's pretty cool. I'm trying to create a page where the Ajax call

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

/

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/noppanit/2y179dgg/

Share Improve this question asked Apr 7, 2016 at 21:41 toytoy 12.2k29 gold badges101 silver badges181 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 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:

  • From SO : Why we need to use flatMap?
  • the nicely presented : The introduction to Reactive Programming you've been missing
  • Official doc : https://github./Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/selectmany.md
  • Illustrative marbles : http://reactivex.io/documentation/operators/flatmap.html

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744724079a4590081.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信