【问题标题】:rxjs6 'share()' does not work with 'of(...)'?rxjs6 'share()' 不能与 'of(...)' 一起使用?
【发布时间】:2018-09-01 03:48:08
【问题描述】:

为什么使用of(...) 创建的 observable 不会在多个订阅者之间共享源? timer(...)Observable.create(...) 按预期工作。我在文档中找不到任何提及。

https://stackblitz.com/edit/typescript-cygjdt?file=index.ts&devtoolsheight=100

【问题讨论】:

    标签: rxjs6


    【解决方案1】:

    它可以工作,但在您的示例中它是同步的:

    // of
    const ofSource = of('hi');
    const ofExample = ofSource.pipe(
      tap(() => console.log('***SIDE EFFECT - OF***'))
    );
    
    const ofSharedExample = ofExample.pipe(share());
    
    ofSharedExample.subscribe(() => console.log('of sub 1'));
    ofSharedExample.subscribe(() => console.log('of sub 2'));
    

    第一个订阅在第二个订阅之前完成。所以share 将取消订阅底层的 observable,因为没有其他订阅者共享 observable。

    但是,如果您添加 observeOn(asyncScheduler)(或其他一些异步行为),您将“延迟”订阅并获得共享的 of

    https://stackblitz.com/edit/typescript-xcwyew?file=index.ts

    【讨论】:

      猜你喜欢
      • 2018-11-25
      • 2017-06-03
      • 1970-01-01
      • 2010-10-30
      • 1970-01-01
      • 1970-01-01
      • 2017-01-09
      • 2017-04-14
      • 2016-09-16
      相关资源
      最近更新 更多