Share Reply - RXJS Operator
In this tutorial, we will learn about the Share Reply operator of RXJS.
Share Reply
By using the shareReply() operator we can Avoid duplicate requests for the same data.
Suppose we have one API request which returns us all users data, now we want to use the same data pf users with different filters, without calling API again, let's how we can do that using Share Reply Operator:
Example:
url = "https://jsonplaceholder.typicode.com/users";
users: Observable<any>;
users2: Observable<any>;
users3: Observable<any>;
ngOnInit() {
this.getData();
}
getData() {
this.users = this.http.get(this.url).pipe(shareReplay());
this.users2 = this.users.pipe(
map((res) =>
res.filter((data) => {
return data["id"] == "2";
})
)
);
this.users3 = this.users.pipe(
map((res) =>
res.filter((data) => {
return data["id"] == "3";
})
)
);
}
The above example will make only one request to API and will share the result to another observable, which avoids making extra API calls and make performance improvements.