Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

EvtLikeToEvt #36

Open
garronej opened this issue Jul 25, 2022 · 0 comments
Open

EvtLikeToEvt #36

garronej opened this issue Jul 25, 2022 · 0 comments

Comments

@garronej
Copy link
Owner

[ ]: 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;

}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant