take-until-destroy
Version:
A simple way to unsubscribe from an RxJs stream in Angular (2+) when the component is destroyed
64 lines • 2.07 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
var rxjs_1 = require("rxjs");
var operators_1 = require("rxjs/operators");
var error_messages_1 = require("./error-messages");
/**
* A Map where the component instance is stored as the key
* and the destroy$ subject as the value
* @type {WeakMap<Object, Observable>}
*/
var instanceDestroy$Map = new WeakMap();
/**
* An RxJs operator which takes an Angular class instance as a parameter. When the component is destroyed, the stream will be
* unsubscribed from.
*
* <b>Important:</b> Make sure you have either {@link Destroyable @Destroyable} decorating your class like so:
* <pre><code>
* @Destroyable
* @Component({
* ...
* })
* export class ExampleComponent {}
* </code></pre>
*
* or that your class implements OnDestroy like so:
* <pre><code>
* @Component({
* ...
* })
* export class ExampleComponent implements OnDestroy {
* ngOnDestroy () {}
* }
* </code></pre>
*
* @example
* <pre><code>
* ngOnInit() {
* this.randomObservable
* .pipe(takeUntilDestroy(this))
* .subscribe((val) => console.log(val))
* }
* </code></pre>
* @param {Object} target (normally `this`)
* @returns {Observable<T>}
*/
exports.takeUntilDestroy = function (target) { return function (stream) {
var originalDestroy = target.ngOnDestroy;
if (!(originalDestroy && typeof originalDestroy === 'function')) {
throw new Error(error_messages_1.ErrorMessages.NO_NGONDESTROY);
}
if (instanceDestroy$Map.has(target)) {
var destroy$FoundInMap = instanceDestroy$Map.get(target);
return stream.pipe(operators_1.takeUntil(destroy$FoundInMap));
}
var newDestroy$ = new rxjs_1.Subject();
instanceDestroy$Map.set(target, newDestroy$.asObservable());
target.ngOnDestroy = function () {
originalDestroy.apply(this, arguments);
newDestroy$.next();
newDestroy$.complete();
};
return stream.pipe(operators_1.takeUntil(newDestroy$.asObservable()));
}; };
//# sourceMappingURL=take-until-destroy.js.map