当内部 observable 完成时,switchMap 似乎没有完成 [英] switchMap does not seem to complete when the inner observable completes

查看:33
本文介绍了当内部 observable 完成时,switchMap 似乎没有完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当谈到 RxJS 时,我仍然是一个菜鸟,但这是我正在尝试做的事情的 JSBin.

I'm still a noob when it comes to RxJS but here's a JSBin of what I am trying to do.

https://jsbin.com/wusalibiyu/1/edit?js,console

我有一个可观察的 'a'(在我的例子中是当前的活动连接),它在连接重新连接时发出一个新对象.它本身就是一个可观察对象,因为它可以重新发出一个新值.

I have an observable 'a' (in my case it's the current active connection) which emits a new object whenever the connection reconnects. It's an observable itself because it can re-emit a new value.

我现在想要一个可在当前连接上执行操作时完成的 observable.当 observable 完成时,该操作会通知它已完成.这是b.

I now want an observable that completes whenever an action is executed on the current connection. That action notifies it is done when the observable for it completes. This is b.

问题在于,当内部 observable 完成时,外部没有完成.如何使外部 observable 完整......我应该在 RxJS5 中使用不同的运算符吗?

The problem is that when the inner observable completes, the outer does not complete. How to make the outer observable complete ... . Is there a different operator I should be using in RxJS5?

推荐答案

如果我正确理解您的要求,您可以使用 materialize/dematerialize 对(注意我重构以及我从未结束战争,让人们停止使用 Observable#create).

If I understand your requirement correctly, you can "lift" the inner stream out using a materialize/dematerialize pair (note I refactored as well as part of my never ending war to get people to stop using 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());
});

这篇关于当内部 observable 完成时,switchMap 似乎没有完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆