是否有可能阻止 Rx.Subject 在像 event.stopPropagation 这样的订阅者中发出?

Is it possible to stop a Rx.Subject from emitting within a subscriber like event.stopPropagation?

使用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

但是,如果您希望能够在 "per item basis" 上工作,则不能使用您现在拥有的结构,因为来自 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