Stateful Observable: loading, errors and combined data in RxJS without the boilerplate
Why I stopped writing tap(() => this.loading = true) . Every Angular codebase I have worked on has the same few lines somewhere, usually in many places: a loading flag set from a tap , an error field set from a catchError , and a shareReplay somewhere in between. It works for the happy path. Then someone adds a second async pipe to the template and the request goes out twice. A failure path…
Stateful Observable is a small library built on top of RxJS that eliminates the need for boilerplate code when working with loading, error, and combined data in Angular applications. The library provides a stateful observable that carries its own loading, error, and inactive state, survives errors, shares itself by default, and can be combined with other stateful observables.
Traditionally, developers have to manually manage loading flags, error fields, and combine streams, which can lead to various issues. For instance, if someone adds a second async pipe to the template, the request may go out twice. If a failure path forgets to reset the loading, the spinner will never go away. Combining streams with other observables can result in multiple loading flags and error fields to merge manually.
Stateful Observable addresses these problems by providing a unified approach to managing loading, error, and combined data. It comes with an npm package named "@rx-evo/stateful-observable," which depends only on RxJS and works in Node.js environments as well.
Using Stateful Observable simplifies the code structure and makes it easier to understand and maintain. For example, a component example provided in the article shows how to replace the boilerplate code with stateful observables. Instead of having three mutable loading subjects, five tap functions, and a manually merged combinedLoading$, the component now only has two stateful observables: clientId$ and allProducts$.
The component with Stateful Observable automatically handles loading, error, and combined data. If the bucket request fails, bucket$ ends, and populatedBucket$ ends with it. Additionally, if a new clientId is provided, it won't affect the stream since it is already dead. Error handling is also built-in, eliminating the need for catchError and error subjects per stream, as well as reducing the manual merging of combinedError$.
In summary, Stateful Observable streamlines the process of handling loading, error, and combined data in Angular applications, reducing boilerplate code and potential issues.
Rewritten by urgent.news; may contain errors — check the original.