将已有订阅者的Observable替换为其他Observable

时间:2019-05-16 09:20:01

标签: rxjs

我有一个Observable,后来得到另一个Observable的“替换”。

如何在不失去订阅者的情况下交换Observable

const source = NEVER

const source2 = interval(1000);

source.subscribe(x => console.log(x));

// source.switch(source2)

source.switch(source2)显然不是有效的操作。但这说明了我想要实现的目标。 在StackBlitz上也是如此:

https://stackblitz.com/edit/rxjs-76a7ew

订阅后我需要做什么,所以这段代码将开始打印interval中的数字?

1 个答案:

答案 0 :(得分:0)

所以您想切换到source2

source.pipe(
 switchMap(() => source2)
).subscribe(x => console.log(x)); // x here is source2

您也可以使用mergeMapconcatMap,但在这种情况下,我建议使用switchMap,因为它将取消先前的发射