One liner state management ft. RxJs

Handling a use-case where we need to retrieve some data, store it and share it to multiple instances across the application

Ankit kaushik
2 min readJan 26, 2023
lightning tracks

Create a data service

export class DataService {

fetchAssignedPatients = () => this.http.get(`assigned-patients-url`);

assignedPatients$ = this.fetchAssignedPatients();

}

Subscribe to the assignedPatients$ in your components and consume it wherever you need it.

this.dataService.assignedPatients$.subscribe((patients) => consume(patients))

The Problem we didn’t solve yet

As many times as we subscribe it, we are re-fetching the data. Think for a moment what would be your approach ?

shareReplay to your rescue

fetchAssignedPatients = () => this.http.get(`assigned-patients-url`).pipe(
shareReplay({bufferSize: 1, refCount: true})
);

For the very first time it’s subscribed, it’ll initiate the API call and afterwards for further subscriptions made the fetched data is replayed or shared to that subscriber.

Benefits reaped with shareReplay

  • Not loading the data until needed
  • Lazy loading the data at the point of request
  • Succinct solution
  • Not creating bunch of dependent states to manage

Introducing dynamic params to re-fetch the API in certain cases

fetchAssignedPatients = () => this.progamChange$.pipe(
switchMap((programId) => this.http.get(`assigned-patients-url?${programId}`)),
shareReplay({bufferSize: 1, refCount: true})
);

In the above snippet we introduced a dependency of programId to our state. In a similar way the other dependencies could be clubbed together using RxJs operators to form the derived state.

Thanks, stay tuned for more such things✌️

--

--