带有 BehaviorSubject 和异步管道的 RxJS share() 运算符 - Angular [英] RxJS share() operator with BehaviorSubject and async pipe - Angular

查看:46
本文介绍了带有 BehaviorSubject 和异步管道的 RxJS share() 运算符 - Angular的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 BehaviorSubject 被用作可观察对象:

I have a BehaviorSubject that is being consumed as an observable:

testForStack$: Observable<boolean>;

ngOnInit(){
    const bs = new BehaviorSubject(true);
    this.testForStack$ = bs
      .asObservable()
      .do(t => console.log('subscribed'))
      .share();
}

这个 observable 是通过模板中的三个 async 管道传输的:

This observable is being piped through three async pipes in the template:

Sub1: {{testForStack$ | async}}<br>
Sub2: {{testForStack$ | async}}<br>
Sub3: {{testForStack$ | async}}

问题只是第一个 (Sub1) 获得 true 的值

The issue is only the first (Sub1) is getting the value of true

Sub1: true
Sub2: 
Sub3:

如果我删除了 .share(),三个值的值都为 true,但这会导致多个订阅的问题.

If I remove the .share(), all three values get the value of true, but this causes the issue of multiple subscriptions.

关于为什么使用 BehaviorSubject 会导致这种行为的任何想法?它被用作 observable,所以我假设上面的代码可以正常工作.

Any thoughts on why using the BehaviorSubject causes this behavior? It's being used as an observable so I would assume the above code would work correctly.

这也类似于这个答案.

推荐答案

这是正确的行为.share() 运算符仅保留对其父级的一个订阅,并且 BehaviorSubject 仅在订阅时发出其值.

This is a correct behavior. The share() operator keeps only one subscription to its parent and BehaviorSubject emits its value only on subscription.

这意味着当你使用第一个 {{testForStack$ |async}} 它在链的末尾订阅 share() 订阅它的父级,这导致订阅源 BehaviorSubject 发出它的值立即.

This means that when you use the first {{testForStack$ | async}} it subscribes at the end of the chain to share() which subscribes to its parents which results in subscribing to the source BehaviorSubject that emits its value immediately.

然而,第二个和所有连续的{{testForStack$ |async}} 订阅 share() ,它已经订阅了它的父级并且不会再订阅,所以没有什么可以将源值推送给这些观察者.

However, the second and all consecutive {{testForStack$ | async}} subscribe to share() which already has subscribed to its parent and won't make any more subscriptions so there's nothing to push the source value to these observers.

一个简单的解决方案可能是使用 shareReplay(1)(取决于你的 RxJS 版本)你应该使用 publishReplay(1).refCount() 代替,因为这些问题(或其 pipable 等价物):

An easy solution could be using shareReplay(1) (depending on your RxJS version) you should probably use publishReplay(1).refCount() instead because of these issues (or its pipable equivalents):

https://github.com/ReactiveX/rxjs/issues/3127

这篇关于带有 BehaviorSubject 和异步管道的 RxJS share() 运算符 - Angular的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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