Development

How to use the RxJS partition function

2 min. read

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 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

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

import { partition, Subject } from 'rxjs';

const numbersSubject = new Subject<number>();
const [evenNumbers$, oddNumbers$] = partition(numbersSubject, (value, index) => value % 2 === 0);

oddNumbers$.subscribe(num => console.log('odds', num));
evenNumbers$.subscribe(num => console.log('evens', num));
Figure 1.0 Splitting a Subject into two observables with partition()

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.

Conclusion

There are many ways to separate and handle 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

Kim Pham

Senior Front-end Web Developer