DEV Community

Tejas Naigaonkar
Tejas Naigaonkar

Posted on • Edited on

RxJs: Does my observable gets unsubscribed if its source observable is unsubscribed?

I am subscribed to an observable - MyObservable.
Source observable of MyObservable is SourceObservable.

Question - Does the subscription to MyObservable is closed (unsubscribed) if the subscription to SourceObservable is closed?

Answer is Yes.

Let's verify this with code.

We'll create a method that returns an observable

const mySourceObservable = (): Observable<number> =>
  interval(2000).pipe(
    takeUntil(interval(5000)),
    map((val: number) => val * 2)
  );
Enter fullscreen mode Exit fullscreen mode

Subscribe to the observable returned by above method and log the values emitted in the console

const subscription = mySourceObservable().subscribe((val: number) =>
  console.log(val)
);
Enter fullscreen mode Exit fullscreen mode

Code to check if the subscription is closed

console.log(subscription);

setTimeout((_) => console.log(subscription), 8000);
Enter fullscreen mode Exit fullscreen mode

Once the subscription to the source observable which is interval(2000) is closed, the subscription to the observable returned by method mySourceObservable() is also closed.

Working solution with explanation using comments is available below, do check out - https://stackblitz.com/edit/rxjs-playground-test-gxhfpsaf?file=index.ts

I hope this helps.

Let me your thoughts.

Best,
Jastya!

Top comments (0)