0

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

Below code is not working

Error: Cannot read property 'unsubscribe' of undefined

    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')
    );

But the following code is working

    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')
    );

Help me understand the reason behind it

c69
  • 19,951
  • 7
  • 52
  • 82

1 Answers1

0

as you mentioned in the title of your question, the first example is synchronous, so you get the first value while still inside of the .subscribe() method. Naturally, observer, which is supposed to have a Subscription object hasn't been initialized yet.

If you want to unsubscribe after receiving a single value I would suggest to use .take(1)

D Pro
  • 1,756
  • 1
  • 8
  • 15