从其他可观察对象切换Rxjs流

时间:2019-10-28 03:37:12

标签: javascript rxjs reactive-programming

我正在用两种不同的方法来研究视频播放器,以告诉观察对象是否应该订阅。它们是_videoInfo $和_exit $。它们是在播放器上调用时发出值的流。

我有一个名为_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: () => {}
});

当$ videoInfo发出值时,如何订阅_data $;当_exit $发出值时,如何取消订阅?

2 个答案:

答案 0 :(得分:1)

observable.subscribe()返回一个Subscription对象,您可以使用该对象来取消订阅。

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: () => {}
});

答案 1 :(得分:1)

操作员方式:

_data$.pipe(skipUntil($videoInfo),takeUntil(_exit$)).subscribe()