"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const Observable_1 = require("rxjs/Observable");
const OuterSubscriber_1 = require("rxjs/OuterSubscriber");
const Subject_1 = require("rxjs/Subject");
const subscribeToResult_1 = require("rxjs/util/subscribeToResult");
/**
 * TakeUntilDestroyedSubscriber subscribes to an observable and automatically
 * unsubscribes when teh provided component is destroyed.
 */
class TakeUntilDestroyedSubscriber extends OuterSubscriber_1.OuterSubscriber {
    constructor(destination, component) {
        super(destination);
        this.onDestroyed = new Subject_1.Subject();
        this.add(subscribeToResult_1.subscribeToResult(this, this.onDestroyed));
        const origOnDestroy = component.ngOnDestroy;
        component.ngOnDestroy = () => {
            this.onDestroyed.next();
            if (origOnDestroy) {
                origOnDestroy.call(component);
            }
        };
    }
    notifyNext() {
        this.complete();
    }
    notifyComplete() {
        // noop
    }
}
/**
 * Operator that implements the TakeUntilDestroyedSubscriber.
 */
class TakeUntilDestroyedOperator {
    constructor(component) {
        this.component = component;
    }
    call(subscriber, source) {
        return source.subscribe(new TakeUntilDestroyedSubscriber(subscriber, this.component));
    }
}
function takeUntilDestroyed(component) {
    // tslint:disable-next-line:no-invalid-this
    return this.lift(new TakeUntilDestroyedOperator(component));
}
exports.takeUntilDestroyed = takeUntilDestroyed;
Observable_1.Observable.prototype.takeUntilDestroyed = takeUntilDestroyed;
