RxJS: Avoiding takeUntil Leaks

Sumit kumar Singh
3 min readMar 26, 2023

RxJS is a powerful reactive programming library that allows developers to build complex asynchronous applications. One of the most useful operators in RxJS is takeUntil, which allows developers to unsubscribe from observables once a specific condition is met. This can be particularly useful for avoiding memory leaks, as it ensures that subscriptions are cleaned up when they are no longer needed.

However, if not used properly, takeUntil can become a source of memory leaks. In this answer, I will discuss in depth how to avoid takeUntil leaks in RxJS with an example.

Let’s consider the following code snippet:

import { interval, Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';

const stop$ = new Subject();

interval(1000)
.pipe(takeUntil(stop$))
.subscribe(
value => console.log(value),
err => console.error(err),
() => console.log('Completed')
);

In this example, we create an observable that emits a value every second using interval(1000). We then use the takeUntil operator to ensure that the subscription is terminated when the stop$ subject emits a value.

However, there is a potential issue with this code. If we don’t explicitly unsubscribe from the stop$ subject, it will remain in memory and continue to emit values even after the subscription has been…

--

--

Sumit kumar Singh
Sumit kumar Singh

Written by Sumit kumar Singh

YouTube: https://shorturl.at/8zZ4B Linkedin: https://shorturl.at/TeLw7 📚 HTML, Angular, React, and JavaScript 🧑‍💻 Tips & tricks on Web Development

Responses (3)