"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.window = void 0;
const Observable_js_1 = require("../Observable.js");
const Subject_js_1 = require("../Subject.js");
const noop_js_1 = require("../util/noop.js");
function window(windowBoundaries) {
    return (source) => new Observable_js_1.Observable((destination) => {
        let windowSubject = new Subject_js_1.Subject();
        destination.next(windowSubject.asObservable());
        const errorHandler = (err) => {
            windowSubject.error(err);
            destination.error(err);
        };
        source.subscribe((0, Observable_js_1.operate)({
            destination,
            next: (value) => windowSubject?.next(value),
            complete: () => {
                windowSubject.complete();
                destination.complete();
            },
            error: errorHandler,
        }));
        (0, Observable_js_1.from)(windowBoundaries).subscribe((0, Observable_js_1.operate)({
            destination,
            next: () => {
                windowSubject.complete();
                destination.next((windowSubject = new Subject_js_1.Subject()));
            },
            complete: noop_js_1.noop,
            error: errorHandler,
        }));
        return () => {
            windowSubject?.unsubscribe();
            windowSubject = null;
        };
    });
}
exports.window = window;