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() {
}
}
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.
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.
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With