Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJS: How to return a cached response until the request parameter values are changed

Tags:

angular

rxjs

I have a request that needs to be checked each time: If the parameter value of the request is changed, the request should be executed, otherwise the request should be skipped and the response of the previous request should be returned instead.

private resultObs$: Observable<any> = new Subject<void>().asObservable();

return merge(
            this.http.get<model>(`${this.apiUrl}`),
            this.resultObs$
            ).pipe(
                shareReplay(1)
            )
like image 693
Sadegh SN Avatar asked Dec 22 '25 20:12

Sadegh SN


1 Answers

If I understand you correctly you want to achieve the following:

  • Cache the response
  • Return the cached response as long as the input-parameter don't change.

Your code could then look something like this:

@Injectable()
export class UserService {
  private cache$!: Observable<User>;
  private previousParameter: string = '';

  constructor(private http: HttpClient) { }

  getUser(userId: string) {
    if (!this.cache$ || userId !== this.previousParameter) {
      this.cache$ = this.requestUser(userId).pipe(
        shareReplay(1)
      );
      this.previousParameter = userId;
    }
    
    return this.cache$;
  }

  private requestUser(userId: string) {
    return this.http.get<User>(API_ENDPOINT);
  }
}

And when you call getUser(), make sure you add take(1) or first() to your pipe so that you don't stay subscribed to a possibly stale observable:

this.userService.getUser('10').pipe(take(1))
                .subscribe(res => console.log('User:', res));
like image 67
kellermat Avatar answered Dec 24 '25 10:12

kellermat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!