UNPKG

reactive-blocs

Version:
48 lines (47 loc) 2.21 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.createActionContext = void 0; const rxjs_1 = require("rxjs"); const operators_1 = require("rxjs/operators"); const utils_1 = require("./utils"); const handleExecution = (action, handler) => __awaiter(void 0, void 0, void 0, function* () { const { id, args } = action; try { const result = yield handler(args); return { id, result }; } catch (err) { return { id, result: err }; } }); const createActionOf = (actionStream, responseStream) => (type, handler) => { return actionStream .pipe((0, operators_1.filter)(action => action.type === type), (0, operators_1.mergeMap)(action => handleExecution(action, handler))) .subscribe(result => responseStream.next(result)); }; const createDispatch = (actionStream, responseStream) => (type, args) => { const action = { id: (0, utils_1.generateId)(), type, args }; const res = responseStream.pipe((0, operators_1.filter)(r => r.id === action.id), (0, operators_1.map)(r => r.result), (0, operators_1.take)(1)); actionStream.next(action); return res; }; const createActionContext = () => { const actionStream = new rxjs_1.Subject(); const responseStream = new rxjs_1.Subject(); const dispatch = createDispatch(actionStream, responseStream); const actionOf = createActionOf(actionStream, responseStream); return { dispatch, actionOf }; }; exports.createActionContext = createActionContext;