UNPKG

@gaubee/flow

Version:

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

48 lines (47 loc) 1.16 kB
import { SharedFlow } from "./shared_flow.js"; /** * 带状态机的 SharedFlow */ export class StateFlow extends 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(); } } export const stateFlow = (initialValue, by) => new StateFlow(initialValue, by);