使用 RxJS 5
,这可能吗?
var source = new Rx.Subject();
source.map((data) => {console.log('map1'); return data;})
.subscribe((data) => {
console.log('subscribe1', data);
if(someCondition) {
source.stop(); //????????
}
});
source.map((data) => {console.log('map2'); return data;})
.subscribe((data) => {
console.log('subscribe2', data);
});
因此,当我调用 source.next("Hello World");
时,只会通知第一个订阅者。当然,这将在 source.stop()
中失败,因为 stop
函数不存在,但这只是为了详细说明我的问题。
是否有一种方法可以做到这一点,比如 event.stopPropagation
呢?
最佳答案
这取决于您对停止传播的期望。您可以调用 source.complete()
这将停止 Subject 并且它永远不会再发出任何东西。
查看演示:https://jsbin.com/geyucuc/3/edit?js,console
但是,如果您希望能够在“每个项目的基础上”工作,您不能使用现在的结构,因为 source
中的每个值都由 Subject 发送给它的两个订阅者.
您没有像 source
=> subscribe1
=> subscribe2
这样的链。
现在您有 source
=> subscribe1
然后是 source
=> subscribe2
。
所以你可以把它做成这样的链,例如:
var source = new Rx.Subject();
source
.map(item => { // wrap this
return { value: item, stopped: false };
})
// your logic
.map((data) => {
console.log('map1', data.value);
// do whatever here
if (data.value == 2) {
data.stopped = true;
}
return data;
})
.filter(item => !item.stopped) // this is your stopPropagation()
.map((data) => {
// do whatever here
console.log('map2', data.value);
return data;
})
.subscribe((data) => {
// do nothing here, just construct the chain.
});
source.next(1);
source.next(2);
打印以下内容:
map1 1
map2 1
map1 2
关于javascript - 是否有可能像 event.stopPropagation 这样阻止 Rx.Subject 在订阅者中发出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41001115/