Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 9 observable unsubscribe using @ngneat/until-destroy npm package

I am using @ngneat/until-destroy this npm package to auto unsubscribe observables. I have used checkProperties: true to auto unsubscribe observables.

But, I am not getting how to test it. Whether observable is getting unsubscribed or not?

My question is simple. Does this code works or do I have to use pipe like this before subscription

.pipe(untilDestroyed(this))

Thank you in advance

import { UntilDestroy, untilDestroyed } from '@ngneat/until-destroy';

@UntilDestroy({ checkProperties: true })

@Component({
  selector: 'app-view-all-purchase',
  templateUrl: './view-all-purchase.component.html',
  styleUrls: ['./view-all-purchase.component.scss']
})

export class ViewAllPurchaseComponent implements OnInit, OnDestroy  {


  ngOnInit() {

 this.subscibe1 =  this.vendorService.five_vendors().subscribe(data => {
    if(data){
      console.log(data)
       this.vendor_list = data
    }})

}

ngOnDestroy() {

 }

}
like image 968
pratik jaiswal Avatar asked May 04 '20 13:05

pratik jaiswal


People also ask

How do I unsubscribe from ngOnDestroy observable?

takeUntil(notifier) See, we pipe the observable to takeUntil before we subscribe. The takeUntil will emit the values emitted by the interval until the notifier Subject emits, it will then unsubscribe the observable$. The best place to make the notifier to emit so the observable$ is canceled is in the ngOnDestroy hook.

Do I need to unsubscribe from observable Angular?

No need to unsubscribe from internal observables of an application scoped service since this service never get's destroyed, unless your entire application get's destroyed, there is no real reason to unsubscribe from it and there is no chance of memory leaks.

Do I need to unsubscribe from observable in service?

You don't need to unsubscribe from observable created by Http or HttpClient because it is finite observable (value will be emitted only once and complete will be called). However, you CAN unsubscribe from the observable created by HttpClient to cancel the request.


1 Answers

To check if your observable is unsubscribed, you can add a console.log to your subscription (you already have that but put if outside of the if(data){} ) and then change the observable in another component after the ViewAllPurchaseComponent should have been destroyed. If you get a console.log from the ViewAllPurchaseComponent when changing the observable in another component, it was not unsubscribed.

I don't know about the '@ngneat/until-destroy', I usually use

ngOnDestroy(){ 
   this.subscibe1.unsubscribe();
}

Hope that helps!

like image 121
Amygdala Avatar answered Oct 17 '22 14:10

Amygdala