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)
)
If I understand you correctly you want to achieve the following:
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With