RxJs:如何基于observable的状态循环? [英] RxJs: How to loop based on state of the observable?

查看:870
本文介绍了RxJs:如何基于observable的状态循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试让RxJs循环遍历流中的Observable,直到它处于某种状态,然后让流继续。具体来说,我正在将同步do / while循环转换为RxJs,但我假设同样的答案也可以用于for或while循环。

I'm trying to get RxJs to loop over an Observable in my stream until it is in a certain state, then have the stream continue. Specifically I'm converting a synchronous do/while loop to RxJs, but I assume the same answer could be used for a for or while loop as well.

我以为我可以使用doWhile(),但似乎条件函数无法访问流中的项目,这似乎打败了我的目的。

I thought I could use doWhile() for this, but it seems like the condition function does not have access to the item in the stream, which seems to defeat the purpose to me.

我不完全确定正确的反应术语对于我想要的是什么,但这里有一个我想要的例子:

I'm not completely sure what the correct reactive terminology is for what I want, but here is an example of what I am going for:

var source = new Rx.Observable.of({val: 0, counter: 3});

source.map(o => {
  o.counter--;
  console.log('Counter: ' + o.counter);

  if (!o.counter) {
    o.val = "YESS!";
  }
  return o;
})
.doWhile(o => { 
  return o.counter > 0; 
})
.subscribe(
    function (x) {
        console.log('Next: ' + x.val);
    },
    function (err) {
        console.log('Error: ' + err);   
    },
    function () {
        console.log('Completed');   
    });

预期产量为:

Counter: 3
Counter: 2
Counter: 1
Counter: 0
Next: YESS!
Completed

假设这是一个可解决的问题,我不清楚你如何标记''循环时你想要返回的地方开始。

Assuming this is a solvable problem, I am unclear on how you mark the 'start' of where you want to return when you loop.

推荐答案

有一个 expand 运算符,允许您递归调用选择器函数。在这种情况下,返回一个空的observable将是你的休息。请参阅 jsbin

There is the expand operator which gets you close by allowing you to recursively call a selector function. Returning an empty observable would be your break in that case. See jsbin:

var source = Rx.Observable.return({val: 0, counter: 3})
    .expand(value =>  { 
      if(!value.counter) return Rx.Observable.empty();
      value.counter -= 1;
      if(!value.counter) value.val = 'YESS';
      return Rx.Observable.return(value)
    })
    .subscribe(value => console.log(value.counter ? 
                                    'Counter: ' + value.counter : 
                                    'Next: ' + value.val));

这篇关于RxJs:如何基于observable的状态循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆