RxJS Crash Course – takeUntil and takeWhile operators


The next operator is takeUntil. This one allows us to complete an observable based on the value of another observable. So, here we have an interval and a timer.

RxJS Crash Course –  takeUntil and takeWhile operators
takeUntil and takeWhile operators

The interval is going to emit values every 500 milliseconds until the timer runs out after 2 seconds, this is a clever way to unsubscribe from data without actually having to call unsubscribe on the observable itself.

So, here we get the first few emitted values then the timer runs out and so it logs complete.

A closely related operator is takeWhile. This one will tell the observable to emit values until a certain condition turns true.

In this example, we have a collection of names and we want to stop the observable once it reaches the name of DasJS.

In other words, we want it to take values while the name does not equal DasJS then we’ll use the finally operator to verify that the observable completed successfully.

So, when we run this in the browser we can see we only get the values that came before DasJS.

Let’s move to the next article: