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)
);
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)
);
Code to check if the subscription is closed
console.log(subscription);
setTimeout((_) => console.log(subscription), 8000);
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!