0

演示:https ://stackblitz.com/edit/rxjs-unsubscribe-issue?file=index.ts

下面的代码不起作用

错误:无法读取未定义的属性“取消订阅”

    const a = (): Observable<any> =>
    new Observable(sub => {
      sub.next(1);
      return () => {
        console.log('unsubscribe');
      };
    });
    const observer = a().subscribe(
      value => {
        console.log('Subscription');
        observer.unsubscribe();
      },
      e => console.log(e),
      () => console.log('complete')
    );

但是下面的代码正在工作

    const b = (): Observable<any> =>
    new Observable(sub => {
      setTimeout(()=>sub.next(1),0);
      return () => {
        console.log('unsubscribe');
      };
    });
    const observer2 = b().subscribe(
      value => {
        console.log('Subscription b');
        observer2.unsubscribe();
      },
      e => console.log(e),
      () => console.log('complete')
    );

帮我理解背后的原因

4

1 回答 1

0

正如您在问题的标题中提到的,第一个示例是同步的,因此您在仍在.subscribe()方法内部时获得了第一个值。自然,observer,它应该有一个Subscription对象还没有被初始化。

如果您想在收到单个值后取消订阅,我建议您使用.take(1)

于 2020-02-12T07:54:35.970 回答