"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.retryWhen = void 0;
const Observable_js_1 = require("../Observable.js");
const Subject_js_1 = require("../Subject.js");
function retryWhen(notifier) {
    return (source) => new Observable_js_1.Observable((destination) => {
        let innerSub;
        let syncResub = false;
        let errors$;
        const subscribeForRetryWhen = () => {
            innerSub = source.subscribe((0, Observable_js_1.operate)({
                destination,
                error: (err) => {
                    if (!errors$) {
                        errors$ = new Subject_js_1.Subject();
                        (0, Observable_js_1.from)(notifier(errors$)).subscribe((0, Observable_js_1.operate)({
                            destination,
                            next: () => innerSub ? subscribeForRetryWhen() : (syncResub = true),
                        }));
                    }
                    if (errors$) {
                        errors$.next(err);
                    }
                },
            }));
            if (syncResub) {
                innerSub.unsubscribe();
                innerSub = null;
                syncResub = false;
                subscribeForRetryWhen();
            }
        };
        subscribeForRetryWhen();
    });
}
exports.retryWhen = retryWhen;