首页 > 解决方案 > Where to put ShareReplay(1) pipe

问题描述

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.

标签: google-cloud-firestorerxjsobservableangularfirerxjs-pipeable-operators

解决方案


是的,你的假设是正确的。

shareReplay(1)基本上缓存最后发出的值。如果将其放在管道的开头,则将为每个订阅者的每个发出的值执行以下所有运算符。将其放在最后将缓存处理后的结果,并且无论有多少订阅者,所有先前的运算符都只会对每个值执行一次。


推荐阅读