I have the following call to Firebase database. If I want to share the result of the observable, where I'd I put the share really(1) ?
get userStacks(): Observable<StackModel[]> {
return this.auth.authState
.pipe(
shareReplay(1), ===>>> HERE ?
switchMap(user => {
if (user) {
return this.db
.collection<StackModel>('stacks', ref =>
ref.where('perm.readers', 'array-contains', user.uid),
)
.valueChanges()
.pipe(shareReplay(1), ===>>> HERE ?
stackList =>
combineLatest([
stackList,
this.dataService.currentNormalOrReverse,
this.idsFilter$,
]).pipe(
shareReplay(1), ===>>> HERE ?
map(([stacks, normalOrReverse]) => [
...StacksService.sortAlphabetical(stacks, normalOrReverse),
]),
),
);
}
return [];
}),
)
.pipe(shareReplay(1)), ===>>> HERE?
}
I suppose it should be the last operation in the chain, just before I'd subscribe to the observable, therefore it should be the last on here. Is my assumption correct? Thank you.
Yes, your assumption is correct.
shareReplay(1)
basically caches the last emitted value. If you put it at the beginning of the pipeline, all the following operators will be performed for each emitted value for each subscriber. Putting it the last will cache the processed result and all the previous operators will only be performed once per value no matter how many subscribers there are.