evt icon indicating copy to clipboard operation
evt copied to clipboard

EvtLikeToEvt

Open garronej opened this issue 1 year ago • 0 comments

[ ]: Use StatefulEvtLike in powerhooks instead of StatefulObservable.

//evtLikeToEvt.ts
import type { NonPostableEvtLike, UnpackEvt, EvtLike } from "./types";
import { importProxy } from "./importProxy";
import type { EvtLikeToEvt } from "./types";
import { assert } from "tsafe/assert";
import { is } from "tsafe/is";

type CtxLike<Result> = import("./types").CtxLike<Result> & {
    evtDoneOrAborted: NonPostableEvtLike<unknown> & { postCount: number; attachOnce(callback: () => void): void; };
};

export function evtLikeToEvt<E extends NonPostableEvtLike<any>>(
		evtLike: E,
		ctx: CtxLike<any>
): EvtLikeToEvt<E> {

	const evt = "state" in evtLike ? importProxy.Evt.create((evtLike as any).state) : importProxy.Evt.create();

	let doSkip = false;

	evt.attach(ctx, data => {
		//NOTE: We received an event so we know it's postable;
		assert(is<EvtLike<UnpackEvt<E>>>(evtLike));
		doSkip = true;
		evtLike.post(data);
		doSkip = false;
	});

	const ctxForEvtLike = importProxy.Evt.newCtx();

	evtLike.attach(ctxForEvtLike, data => {
		if (doSkip) {
			return;
		}
		evt.post(data);
	});

	ctx.evtDoneOrAborted.attach(() => ctxForEvtLike.done());

	return evt as any;

}

garronej avatar Jul 25 '22 20:07 garronej