"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.tap = void 0;
const Observable_js_1 = require("../Observable.js");
const identity_js_1 = require("../util/identity.js");
function tap(observerOrNext) {
    const tapObserver = (0, Observable_js_1.isFunction)(observerOrNext) ? { next: observerOrNext } : observerOrNext;
    return tapObserver
        ? (source) => new Observable_js_1.Observable((destination) => {
            tapObserver.subscribe?.();
            let isUnsub = true;
            source.subscribe((0, Observable_js_1.operate)({
                destination,
                next: (value) => {
                    tapObserver.next?.(value);
                    destination.next(value);
                },
                error: (err) => {
                    isUnsub = false;
                    tapObserver.error?.(err);
                    destination.error(err);
                },
                complete: () => {
                    isUnsub = false;
                    tapObserver.complete?.();
                    destination.complete();
                },
                finalize: () => {
                    if (isUnsub) {
                        tapObserver.unsubscribe?.();
                    }
                    tapObserver.finalize?.();
                },
            }));
        })
        :
            identity_js_1.identity;
}
exports.tap = tap;