Reputation: 79
const a$ = new BehaviorSubject(['a']).pipe(
// op.share() does not have share
);
a$.subscribe((a) => {
console.log('a$', a)
})
const b$ = new BehaviorSubject([1]);
const c$ = b$.pipe(
op.withLatestFrom(a$)
)
c$.subscribe(c => {
console.log('c$ test', c) // you can find logs in console
})
but if I add a share to a$, subscription of c fail to run.
const a$ = new BehaviorSubject(['a']).pipe(
op.share()
);
a$.subscribe((a) => {
console.log('a$', a)
})
const b$ = new BehaviorSubject([1]);
const c$ = b$.pipe(
op.withLatestFrom(a$)
)
c$.subscribe(c => {
console.log('c$ test', c) // logs here cannot be found in console
})
I cannot understand why this happened. and I do need a$ to be shared. Is there any solution for this.
Upvotes: 0
Views: 348
Reputation: 14099
share
doesn't replay values to late subscribers, so you lose the replay functionality of your BehaviorSubject. The first subscription to a$
triggers a subscribe to the BehaviorSubject and share
forewards its value. When you subscribe a second time to a$
share
has already subscribed to the BehaviorSubject so it won't get its value again and, as share
has no replay functionality, won't replay its value.
If your source is a BehaviorSubject and you don't use any other operators you don't need to share it.
If your source is acutally something else your can use shareReplay(1)
instead of share
to replay its latest value to late subscribers.
Upvotes: 3