Using the async
pipe is not always possible. Sometimes we simply have to manually subscribe to observables.
In turn, this means manually unsubscribing to avoid memory leaks.
There are different approaches out there to unsubscribe, but the end result is always the same... Import something, declare a variable, implement ngOnDestroy()
, use when subscribing.
Destroyable
saves us time on implementing boilerplate code and lets you easily subscribe to an observable without any headaches.
Once your class extends Destroyable
, you will be able choose between:
takeUntil(this.destroyed)
.this.subscribe(...)
.In the following example, both methods will create an observable that will unsubscribe on destroy:
If you need to provide your own implementation for
ngOnDestroy()
make sure you callsuper.ngOnDestroy()
in your implementation.