UNPKG

@rxx/worker

Version:

React MVI micro framework.

91 lines (90 loc) 3.35 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var rxjs_1 = require("rxjs"); var operators_1 = require("rxjs/operators"); var MAX_HISTORY_LENGTH = 10; var SubjectTree = (function () { function SubjectTree() { this.subject = new rxjs_1.Subject(); this.state = { view: {} }; this.preservation = []; this.shouldImmediateDispatch = true; this.lastDispatched = null; this.histories = []; this.subscribers = []; } SubjectTree.prototype.setState = function (state) { this.state = state; }; SubjectTree.prototype.subscribe = function (callback) { this.subscribers.push(callback); }; SubjectTree.prototype.unsubscribe = function (callback) { this.subscribers = this.subscribers.filter(function (s) { return s !== callback; }); }; SubjectTree.prototype.unsubscribeAll = function () { this.subscribers = []; }; SubjectTree.prototype.notify = function (payload) { this.shouldImmediateDispatch = false; if (payload.type === 'RETRY') { var target = payload.payload ? this.findHistory(payload.payload) : this.histories[this.histories.length - 1]; if (target) { this.doNotify(target); this.notifySubscribers(target); } return; } this.doNotify(this.createSubjectPayload(payload)); }; Object.defineProperty(SubjectTree.prototype, "observable", { get: function () { return this.subject.pipe(operators_1.share()); }, enumerable: true, configurable: true }); SubjectTree.prototype.getLastDispatched = function () { return this.lastDispatched; }; SubjectTree.prototype.notifySubscribers = function (payload) { this.subscribers.forEach(function (a) { return a(payload); }); }; SubjectTree.prototype.doNotify = function (payload) { var _this = this; this.histories.push(payload); if (this.histories.length >= MAX_HISTORY_LENGTH) { this.histories.shift(); } this.lastDispatched = payload; this.subject.next(payload); if (this.preservation.length) { var preservations = this.preservation.slice(); this.preservation.length = 0; preservations.forEach(function (preserved) { return _this.notify(preserved); }); } this.shouldImmediateDispatch = true; }; SubjectTree.prototype.findHistory = function (retryKey) { return this.histories.filter(function (_a) { var type = _a.type; return type === retryKey; })[0] || null; }; SubjectTree.prototype.createSubjectPayload = function (payload) { var _this = this; return tslib_1.__assign({}, payload, { states: this.state.view, dispatch: function (type, payload) { if (_this.shouldImmediateDispatch) { _this.notify({ type: type, payload: payload }); } else { _this.preservation.push({ type: type, payload: payload }); } } }); }; return SubjectTree; }()); exports.SubjectTree = SubjectTree;