[英]Toggle Rxjs stream from other observables
I'm working on a video player with two distinguishing ways to tell whether an observable should be subscribed to or not.我正在开发一个视频播放器,它有两种不同的方式来判断是否应该订阅 observable。 they are _videoInfo$ and _exit$.它们是 _videoInfo$ 和 _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.我有一个名为 _data$ 的可观察对象,它发出我需要跟踪的所有值,但我只想在视频播放器播放时订阅它。
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$.它目前不起作用,因为我无法取消订阅 _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?如何在 $videoInfo 发出值时订阅 _data$ 并在 _exit$ 发出值时取消订阅?
observable.subscribe()
returns a Subscription
object which you can use to unsubscribe. observable.subscribe()
返回一个Subscription
object,您可以使用它来取消订阅。
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: () => {}
});
The operator way:运营商方式:
_data$.pipe(skipUntil($videoInfo),takeUntil(_exit$)).subscribe()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.