说到 RxJS,我还是个菜鸟,但这里有一个 JSBin,展示了我正在尝试做的事情。
https://jsbin.com/wusalibiyu/1/edit?js,console
我有一个可观察的“a”(在我的例子中它是当前事件的连接),每当连接重新连接时它都会发出一个新对象。它本身就是一个可观察值,因为它可以重新发出一个新值。
我现在想要一个在当前连接上执行操作时完成的可观察对象。当其可观察对象完成时,该操作会通知它已完成。这是b。
问题在于,当内部可观察对象完成时,外部可观察对象并未完成。如何使外部可观察的完整......我应该在 RxJS5 中使用不同的运算符吗?
最佳答案
如果我正确理解您的要求,您可以使用materialize
“提升”内部流。/dematerialize
对(请注意,我进行了重构,也是我永无休止的 war 的一部分,以让人们停止使用 Observable#create )。
JsBin (摘录如下)
function b(a) {
// Emit and complete after 100 millis
return Rx.Observable.timer(100)
// Ignore any values emitted
.ignoreElements()
// Emit the value on start
.startWith(a)
.do(() => console.log('creating observable'))
.finally(() => console.log('b done'));
}
var a$ = Rx.Observable.from(['a', 'b'])
.finally(() => console.log('a done'));
var result$ = a$.switchMap(function(a) {
console.log('switching map for a to b', a);
// This "materializes" the stream, essentially it maps complete -> next
return b(a).materialize();
})
// This does the opposite, and converts complete events back,
// but since we are now in the outer stream
// this results in the outer stream completing as well.
.dematerialize()
.share();
result$.subscribe(function(value) {
console.log('value', value);
}, function(e) {
console.error('e', e);
}, function() {
console.log('completed!');
})
result$.toPromise().then(function(data) {
console.log('this should trigger!?', data);
}, function(e) {
console.error('boom', e.toString());
});
关于rxjs - 当内部可观察完成时,switchMap 似乎没有完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40611203/