UNPKG

@gaubee/flow

Version:

启发于 kotlin 的 flow,针对 js/ts 开发人员设计的接口,通常可以作为一个事件管理器

53 lines (52 loc) 1.35 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.stateFlow = exports.StateFlow = void 0; const shared_flow_js_1 = require("./shared_flow.js"); /** * 带状态机的 SharedFlow */ class StateFlow extends shared_flow_js_1.SharedFlow { constructor(initialValue, by) { super(by); this.#value = initialValue; } #value; get value() { return this.#value; } set value(value) { this.emit(value); } /** * 附加监听 * 同 watch * @deprecated 使用 watch */ on(cb, options) { return this.watch(cb, options); } /** * 附加监听 * 可以自定义唯一索引 key,如果重复,会移除之前的监听 */ watch(cb, options) { // 订阅时立即发送当前值 if (options?.immediate) { cb(this.#value); } return super.watch(cb, options); } watchImmediate(cb, options) { return this.watch(cb, { ...options, immediate: true }); } emit(value) { if (this.#value !== value) { this.#value = value; super.emit(value); } return Promise.resolve(); } } exports.StateFlow = StateFlow; const stateFlow = (initialValue, by) => new StateFlow(initialValue, by); exports.stateFlow = stateFlow;