带有行为主题和异步管道的Rxjs share()运算符-Angular [英] Rxjs share() operator with Behavior subject and async pipe - 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();
}
此可观察对象通过模板中的三个异步管道进行管道传输:
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导致此行为的想法?它被用作观察对象,因此我认为上面的代码可以正常工作.
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.
这也与此答案类似:
https://stackoverflow.com/a/40819423/4912604
推荐答案
这是正确的行为. 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()
,该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()
:
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
这篇关于带有行为主题和异步管道的Rxjs share()运算符-Angular的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!