bluehost-banner
Share Reply - RXJS Operator

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.

Subscribe to our Newsletter

Stay up to date! Get all the latest posts delivered straight to your inbox.

If You Appreciate What We Do Here On TutsCoder, You Should Consider:

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Support Us

We are thankful for your never ending support.

You might also like

Leave a Comment