RxJS:我怎么能做“if”与Observables? [英] RxJS: How can I do an "if" with Observables?
本文介绍了RxJS:我怎么能做“if”与Observables?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有两个observable和一个我想听一个observable的变化,如果另一个匹配某个条件。我尝试使用 zip
,但似乎我只会收到通知,如果两个 observables都发生了变化,但我希望在每次更改时收到通知一个可观察的,如果另一个的条件是真的。
Say I have two observables and one I want to listen on changes in one observable, if the other on matches a certain condition. I tried it with zip
but it seems I will only be notified, if both observables change, but I want to be notified for every change on the one observable, if the condition of the other one is true.
我尝试了什么:
var firstState = new Rx.BehaviorSubject(undefined);
var secondState = new Rx.BehaviorSubject(undefined);
Rx.Observable.zip(firstState, secondState, function (first, second) {
return {
first: first,
second: second
}
}).filter(function (value) {
return value.first !== undefined;
}).subscribe(function (value) {
// do something with value.second
});
我注意到有一个 Rx.Observable.if
,但我无法工作。
I noticed there is an Rx.Observable.if
, but I couldn't got it to work.
推荐答案
使用 pausable :
secondState
.pausable(firstState.map(function (s) { return s !== undefined; }))
.subscribe(function (second) {
// only occurs when first is truthy
});
这篇关于RxJS:我怎么能做“if”与Observables?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文