【问题标题】:switchMap does not seem to complete when the inner observable completes当内部 observable 完成时,switchMap 似乎没有完成
【发布时间】:2017-03-29 09:59:03
【问题描述】:

说到 RxJS,我仍然是个菜鸟,但这是我正在尝试做的 JSBin。

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

我有一个可观察的“a”(在我的情况下是当前的活动连接),只要连接重新连接,它就会发出一个新对象。它本身就是一个 observable,因为它可以重新发出一个新值。

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

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

【问题讨论】:

    标签: rxjs rxjs5


    【解决方案1】:

    如果我正确理解您的要求,您可以使用 materialize/dematerialize 对“提升”内部流(请注意,我进行了重构以及我永无止境的战争的一部分,以使人们停止使用 @987654326 @)。

    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());
    });
    

    【讨论】:

    • 我尽可能地从我的项目中复制代码,以便尽可能地复制这种情况。在我的代码中,我将第三方库包装成可观察的。我相信在这种情况下它是正确的。但是,物化/非物化显然是我错过的。非常感谢您提供解决方案!
    猜你喜欢
    • 1970-01-01
    • 2019-05-24
    • 2020-08-11
    • 2023-04-07
    • 2022-01-04
    • 2018-10-06
    • 2021-03-01
    • 2016-01-31
    • 2017-07-20
    相关资源
    最近更新 更多