"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.bufferWhen = void 0;
const Observable_js_1 = require("../Observable.js");
const noop_js_1 = require("../util/noop.js");
function bufferWhen(closingSelector) {
    return (source) => new Observable_js_1.Observable((subscriber) => {
        let buffer = null;
        let closingSubscriber = null;
        const openBuffer = () => {
            closingSubscriber?.unsubscribe();
            const b = buffer;
            buffer = [];
            b && subscriber.next(b);
            (0, Observable_js_1.from)(closingSelector()).subscribe((closingSubscriber = (0, Observable_js_1.operate)({
                destination: subscriber,
                next: openBuffer,
                complete: noop_js_1.noop,
            })));
        };
        openBuffer();
        source.subscribe((0, Observable_js_1.operate)({
            destination: subscriber,
            next: (value) => buffer?.push(value),
            complete: () => {
                buffer && subscriber.next(buffer);
                subscriber.complete();
            },
            finalize: () => (buffer = closingSubscriber = null),
        }));
    });
}
exports.bufferWhen = bufferWhen;