I want to re-use the result of an RxJS stream without executing it again.
In a component I have to Input() streams: query$
and category$
. I want to convert that into two streams that share the same API source. Right now it is making two requests. I'd like to have only one request.
Simplified code:
this.searchResults$ = this.query$
.switchMap((query) => this.httpClient.get(`/whatever?q=${query}`));
this.filteredSearchResults$ = Observable
.combineLatest(this.searchResults$, this.category$)
.filter(([ searchResults, category ]) => {
// Code to make a subset
return ['a', 'subset'];
});
I consume both searchResults$ and filteredSearchResults$ in the same component:
<ng-container *ngIf="(searchResults$ | async) as searchResults">
<ng-container *ngIf="(filteredSearchResults$ | async) as filteredSearchResults">
</ng-container>
</ng-container>
Now I understand why there are two API calls. I just don't see any way to prevent it.
You might want to use share
:
this.searchResults$ = this.query$
.switchMap((query) => this.httpClient.get(`/whatever?q=${query}`))
.share(); <-- HERE
this.filteredSearchResults$ = Observable
.combineLatest(this.searchResults$, this.category$)
.filter(([ searchResults, category ]) => {
// Code to make a subset
return ['a', 'subset'];
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.