Reputation: 655
I'm working on a video player with two distinguishing ways to tell whether an observable should be subscribed to or not. they are _videoInfo$ and _exit$. They are streams that emit values when invoked on the player.
I have an observable called _data$, which emits all the values I need to track, but I only want to subscribe to it when the video player is playing.
I know that the following approach is incorrect, but it explains what I am trying to achieve. It currently does not work, because I can't unsubscribe from _data$.
const _data$ = data$.subscribe(event => {
// data I need when video is playing
});
_videoInfo$.subscribe((res): void => {
// when res emits it means a new video is starting
_data$.subscribe();
});
_exit$.subscribe({
next: () => {
_data.unsubscribe(); // this does not work, but i want to unsubscribe here
},
error: () => {},
complete: () => {}
});
How can I subscribe to _data$ when $videoInfo emits a value and unsubscribe from it when _exit$ emits a value?
Upvotes: 1
Views: 328
Reputation: 11345
The operator way:
_data$.pipe(skipUntil($videoInfo),takeUntil(_exit$)).subscribe()
Upvotes: 1
Reputation: 8481
observable.subscribe()
returns a Subscription
object which you can use to unsubscribe.
let subscription;
_videoInfo$.subscribe((res): void => {
// when res emits it means a new video is starting
subscription = _data$.subscribe();
});
_exit$.subscribe({
next: () => {
if (subscription) {
subscription.unsubscribe();
}
},
error: () => {},
complete: () => {}
});
Upvotes: 1