Joy Biswas
Joy Biswas

Reputation: 6527

unsubscribe to an Observable created by of

When I create an observable and I am done with it I unsubscribe it directly

const data$ = this.httpClient.get('https://jsonplaceholder.typicode.com/todos/1').subscribe(res => {
  console.log('live', res);
  data$.unsubscribe(); // <---- works fine
});

But say if I create an Observable using of and try to do the same

const obs$ = of(1).subscribe(e => {
  console.log('test', e)
  obs$.unsubscribe(); // <--- Problem while creating Observable by of
});

Whats different between these 2 observables?

Upvotes: 2

Views: 639

Answers (3)

Will Alexander
Will Alexander

Reputation: 3571

For ensuring unsubscription in a component, I would recommend creating a Subject which emits in ngOnDestroy() like this:

destroy$ = new Subject<boolean>();
...
ngOnDestroy() {
  this.destroy$.next(true);
}

And adding a takeUntil on each Observable in the component:

myObs$.pipe(
  takeUntil(this.destroy$),
  tap(stuff => doStuff())
).subscribe();

This way you avoid polluting things with loads of unnecessary Subscription variables.

Upvotes: 0

Tarek Selem
Tarek Selem

Reputation: 1

If you have only one observable in your component that would be the easiest scenario for unsubscribing by the following way:

ngOnDestroy() { this.subscription$.unsubscribe(); }

the more complex scenario is having multiple observables, at that moment you will not to push each observable while subscribing in subscriptions: Subscription[] and while destroying do unsubscribe all added subscriptions in the array ngOnDestroy(){ this.subscriptions.forEach(sub => sub.unsubscribe()); }

or you can use that npm package

Upvotes: 0

Tony
Tony

Reputation: 20142

Your code should be import Subscription and unsubscribe in ngOnDestroy

import { Observable, Subscription, of } from "rxjs";
private subscription$: Subscription;

this.subscription$ = of(1).subscribe(e => {
  console.log('test', e)
});

ngOnDestroy() {
 this.subscription$.unsubscribe();
}

Update: What I understand is http request is an observable that potentialy have incoming value in the future and of simply create a list of observable

And from @cartant comment

of completes synchronously, so you are attempting to call obs$.unsubscribe before the assignment to obs$ has been made.

Upvotes: 2

Related Questions