RxJS–Unsubscribe automatically –part 47
I am searching for a simple method to unsubscribe from Observables. Some of methods are detailed here : https://blog.bitsrc.io/6-ways-to-unsubscribe-from-observables-in-angular-ab912819a78f
I do not want
- remember to unsubscribe
- being forced to use html ( the async pipe)
- take operator – I want later to cache first data and then make the http call
- first operator – same with 3
- decorator – seems ok.
- tsLint – no, can be easy to disable
So Decorator it is. More reading
https://www.typescriptlang.org/docs/handbook/decorators.html
https://netbasal.com/automagically-unsubscribe-in-angular-4487e9853a88
Added code the autoUnsub
export function AutoUnsub( constructor ) {
const original = constructor.prototype.ngOnDestroy;
console.log(‘from unsubscribe’);
constructor.prototype.ngOnDestroy = function() {
// tslint:disable-next-line: forin
for ( const prop in this ) {
const property = this[ prop ];
if ( property && (typeof property.unsubscribe === ‘function’) ) {
console.log(‘unsubscribe !’);
property.unsubscribe();
}
}
console.log(‘finish unsub’);
// tslint:disable-next-line: no-unused-expression
original && typeof original === ‘function’ && original.apply(this, arguments);
};
}
Modified code to make property of unsubscribe, e.g. from
this.banksService.GetBanksIds().subscribe(
it=>{
console.log(it.length);
this.banks=it;
},
err=> window.alert(“error:”+ JSON.stringify(err))
)
}
to
banksObs: Observable<string[]>;
//ommitted code
this.banksObs = this.banksService.GetBanksIds();
this.banksObs.subscribe(
it => {
console.log(it.length);
this.banks = it;
},
err => window.alert(‘error:’ + JSON.stringify(err))
);
Created also a new component, for programmers, in order to observe the unsubscribe moving from component to component,
See commit https://github.com/ignatandrei/InfoValutar/commit/66e358848652ce761cb6ef2d69a460f052b12e09
Infovalutar
And one hour passes...(This is the result of 1 hour per day auto-challenge as a full cycle developer for an exchange rates application)
( You can see the sources at https://github.com/ignatandrei/InfoValutar/ )
Leave a Reply