RxJs:如何根据可观察的状态进行循环? [英] RxJs: How to loop based on state of the observable?

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

问题描述

我试图让 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:如何根据可观察的状态进行循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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