How to use the RxJS partition function
Here is a quick guide for using the partition() function in place of if/else statements inside .subscribe() when working with an RxJS Observable.
*Please note that this article discusses the partition function, not operator. See RxJS documentation for the deprecation of partition operator.
What is an Observable?
An RxJS Observable produces values over time and allows the handling of various asynchronous streams of data. Much of logic and other handling is defined in the .subscribe() function of an observable, but operators and functions further enhance the managing logic and events.
Using the partition() function
The logic for values emitted by an Observable can be implemented inside the .subscribe() block – this includes function calls, conditional/if-else statements, and more. However, instead of an if/else statement, you can split an observable into two separate observables based on a condition that you provide using the partition function.
Example usage of partition() with a Subject
A Subject is a special type of observable and is also an observer. Figure 1.0 demonstrates how to use the partition() function with a Subject, where the first parameter takes an observable (in this case, a Subject) and processes the emitted values from that observable based on the second parameter. The second parameter takes a condition that will be used to separate the values that pass said condition vs the values that fail the condition. In turn, two streams are returned and can be used for much cleaner mitigations and better code readability.
There are many ways to separate and handle the logic of Observables' emitted values, such as pipe operators and if-else statements in the .subscribe() block. However, we've found that using partition() is a cleaner, more readable approach that avoids lengthy conditional logic inside your subscribe functions. Reach out to us with any questions.
We hope you enjoyed this article and encourage you to try it out on your next project. Happy coding!
Photo by Javier Allegue Barros