Following the cached service pattern I'm using a BehaviourSubject subscribed by using a read-only Observable created from it in various components
// credential.service.ts
private _credentialList$: BehaviorSubject<Credential[]>
readonly credentialListObv$: Observable<Credential[]>
...
this. credentialListObv$ = this.credentialList$.asObservable()
...
getCredentialList(...): Observable<Credential[]> {
return this.http.get<Credential[]>(
``
).pipe(
tap(credList => {
...
this._credentialList$.next(credList)
}),
)
}
So from the component I trigger the getCredentialList method to emit the fetched list by the _credentialList$ subject and so all the subscribers to the credentialListObv$ should get the value.
The problem is that when I create my component I will get unwanted subscription when I invoke the getCredentialList method
// credential-list.component.ts
private _credentials$: Observable<Credential[]>
constructor(
private credentialService: CredentialService,
) {
this._credentials$ = this.credentialService.credentialListObv$.pipe(
tap(() => {console.log("sub")}),
...
)
}
ngAfterViewInit(): void {
this.credentialService.getCredentialList(...).subscribe()
}
get credentials$() {
return this._credentials$
}
// credential-list.component.html
<mat-expansion-panel *ngFor="let credential of credentials$ | async; let i=index">
...
The result is that when I access the page "sub" will be printed twice. The first subscription happens from the async pipe inside the component template but why there is another one if I will never invoke subscribe on this._credentials$ from credential-list component?