从使用 switch 构建的 observables 接收完成的通知 [英] Receiving done notifications from observables built using switch
问题描述
在下面的示例中,foo
从 bar
接收数据,但在 bar
完成时忽略.foo
在 baz
完成时完成,这不是我想要的行为.
In the below example, foo
receives data from bar
yet ignores when bar
completes. foo
is completed when baz
completes, which is not the behavior I desire.
var baz = Rx.Observable.interval( 50 ).take( 10 );
var foo = baz
.select(function (x) {
var bar = Rx.Observable.range(x, 3);
return bar;
})
.switch();
是否有 switch
的变体或我可以使用的技术使新创建的 foo
observable 与 bar
具有相同的生命周期?也就是说,我希望 foo
在 bar
完成的情况下完成.
Is there a variant of switch
or a technique that I could use to have the newly created foo
observable have the same lifetime as bar
? That is, I would like foo
to complete in the event that bar
completes.
解决方案:
var baz = Rx.Observable.interval( 50 ).take( 10 );
var foo = baz
.select(function (x) {
var bar = Rx.Observable.range(x, 3).materialize()
return bar;
})
.switch()
.dematerialize();
推荐答案
onCompleted()
根据定义是一个终端案例,所以你不能直接接收 onCompleted()
外部 Observable
.
onCompleted()
is by definition a terminal case so no you cannot receive onCompleted()
directly in the outer Observable
.
根据您需要如何使用 onCompleted
,您有几个选项.
You have a couple options depending on how you need to use the onCompleted
.
您可以使用 .tapOnCompleted()
或 .finally()
来处理流终止的副作用:
Either you could use .tapOnCompleted()
or .finally()
to handle a side effect of stream termination:
var foo = Rx.Observable.range(0, 3)
.select(function (x) {
return Rx.Observable.range(x, 3)
.tapOnCompleted(function(){/*Apply side effect*/});
//Or .finally()
})
.switch();
或者你需要实现
内部流来处理值:
Or you will need to materialize
the inner stream to handle the values:
var foo = Rx.Observable.range(0, 3)
.select(function (x) {
var bar = Rx.Observable.range(x, 3)
.materialize();
return bar;
})
.switch()
foo.subscribe(function(x) {
if (x.kind == 'N') {
process(x.value);
} else if (x.kind == 'C') { /*Do something else*/}
});
请注意,在您给出的示例中,当 switch
发生时,Observable
不会完成,只有最后一个会完成,因为后续值传入的速度太快.
Note that in the example you gave when the switch
occurs the Observable
will not complete, only the last one will complete, because subsequent values are coming in too fast.
如果所有的序列都应该运行直到完成,你应该使用 concatAll()
而不是 switch()
If all of the sequences should be running until completed you should use concatAll()
instead of switch()
这篇关于从使用 switch 构建的 observables 接收完成的通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!