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

Improve DX around withPubSub #4

Open
christoph-fricke opened this issue Oct 6, 2021 · 0 comments
Open

Improve DX around withPubSub #4

christoph-fricke opened this issue Oct 6, 2021 · 0 comments
Labels
enhancement New feature or request help wanted Extra attention is needed

Comments

@christoph-fricke
Copy link
Owner

christoph-fricke commented Oct 6, 2021

The idea of withPubSub is to extend a given behavior with the ability to publish event. Most importantly, the type for published events should be different from the type for received event, because an actor does not have to only publish events it can receive.

The current generics make it rather awkward to type the publishable events. As soon as the generic P gets defined, a user has to also provide types for the other generics. When defaults are used for the remainder, the wrapped behavior does not correctly infer its types from the given behavior.

To avoid this, a user currently has to type the published events like this: withPubSub((pub: Publish<Event>) => behavior).

Ideally, this should work: withPubSub<Event>((pub) => behavior) and should correctly infer the receive-able events and state from behavior.

I tried this, but it does not work as the resulting behavior will be typed as Behavior<any, any>:

export function withPubSub<P extends EventObject>(
	getBehavior: (publish: Publish<P>) => Behavior<any>
): ReturnType<typeof getBehavior> extends Behavior<infer E, infer S>
	? WithPubSub<P, Behavior<E, S>>
	: never {
	const subscribers = createSubscriberStructure<P>();
	const behavior = getBehavior(createPublishFunction(subscribers));

	return {
		...behavior,
		transition: (state, event, ctx) => {
			if (handleSubscribeEvent(subscribers, event)) return state;

			return behavior.transition(state, event, ctx);
		},
	};
}
@christoph-fricke christoph-fricke added enhancement New feature or request help wanted Extra attention is needed labels Oct 6, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request help wanted Extra attention is needed
Projects
None yet
Development

No branches or pull requests

1 participant