In the react-world something I’ve really enjoyed using is the SWR library for fetching data which allows consolidation of data into a hook that can be used to track error and loading states as well as keep the data accessible at all times for consuming components
Implementing this with RxJS
In RxJS we work with data as a stream, when fetching data we often have a resulting stream that will emit a value once the data has been fetched. The problem with this methodology is that we only have the resultant data but errors and loading states are not easily surfaced to consumers of this data unless they hook into the entire lifecycle for the momment the stream is created
Below is an implementation of a class that enables the definition and management of multiple streams that consumers can access for resolving the respective states for a given request. Furthermore, requests are triggered by params observable such that each emission of the observable will trigger the fetcher. Hence, this can be used for loading data but also for working with forms where each submission is a .next to the params stream
Additionally, we can define some utilities for the above class to use:
Using the Class
We can use the class we defined by creating an instance of it
The users$, isLoading$ and hasError$ values above are streams that we can use with our normal RxJS code
Interacting with the data is also pretty neat now, for example we can trigger the data to be refreshed whenever someone updates the search in our UI by doing something like:
Which will then trigger the data to be refreshed and all the loading and error states to be updated accordingly