是否可以阻止Rx.Subject在event.stopPropagation之类的订阅者中发出?

时间:2016-12-06 17:13:56

标签: javascript rxjs rxjs5

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

1 个答案:

答案 0 :(得分:2)

这取决于您对停止传播的期望。你可以调用source.complete()来阻止主题,它将永远不会发出任何东西。

请参阅演示:https://jsbin.com/geyucuc/3/edit?js,console

但是,如果您希望能够“基于每个项目”工作,那么您现在无法使用您所拥有的结构,因为source中的每个值都会被主题发送给其订阅者。

您没有值,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