From d6256a7cfd825c0b2f464758c9f7a051097a59b9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Julien=20Valverd=C3=A9?= Date: Sun, 4 May 2025 01:18:29 +0200 Subject: [PATCH] Stream hooks work --- packages/reffuse/src/ReffuseNamespace.ts | 29 +++++++++++++++++------- 1 file changed, 21 insertions(+), 8 deletions(-) diff --git a/packages/reffuse/src/ReffuseNamespace.ts b/packages/reffuse/src/ReffuseNamespace.ts index 9de86e3..b7ac754 100644 --- a/packages/reffuse/src/ReffuseNamespace.ts +++ b/packages/reffuse/src/ReffuseNamespace.ts @@ -483,12 +483,18 @@ export abstract class ReffuseNamespace { return stream } - useSubscribeStream( + useSubscribeStream( this: ReffuseNamespace, stream: Stream.Stream, - initialValue?: InitialA, + initialValue?: () => Effect.Effect, ): InitialA extends A ? Option.Some : Option.Option { - const [reactStateValue, setReactStateValue] = React.useState>(Option.fromNullable(initialValue)) + const [reactStateValue, setReactStateValue] = React.useState>(this.useMemo( + () => initialValue + ? Effect.map(initialValue(), v => Option.some(v as A)) + : Effect.succeed(Option.none()), + [], + { doNotReExecuteOnRuntimeOrContextChange: true }, + )) this.useFork(() => Stream.runForEach( Stream.changesWith(stream, (x, y) => x === y), @@ -498,17 +504,24 @@ export abstract class ReffuseNamespace { return reactStateValue as InitialA extends A ? Option.Some : Option.Option } - usePullStream( + usePullStream( this: ReffuseNamespace, stream: Stream.Stream, - initialValue?: InitialA, + initialValue?: () => Effect.Effect, ): [ latestValue: InitialA extends A ? Option.Some : Option.Option, pull: Effect.Effect, Option.Option>, ] { const scope = this.useScope([stream]) - const [reactStateValue, setReactStateValue] = React.useState>(Option.fromNullable(initialValue)) + const [reactStateValue, setReactStateValue] = React.useState>(this.useMemo( + () => initialValue + ? Effect.map(initialValue(), v => Option.some(v as A)) + : Effect.succeed(Option.none()), + [], + { doNotReExecuteOnRuntimeOrContextChange: true }, + )) + const pull = this.useMemo(() => Effect.context().pipe( Effect.flatMap(context => Stream.toPull(Stream.changesWith(stream, (x, y) => x === y)).pipe( Effect.map(effect => effect.pipe( @@ -567,11 +580,11 @@ export abstract class ReffuseNamespace { return props.children(this.useRefState(props.ref)) } - SubscribeStream( + SubscribeStream( this: ReffuseNamespace, props: { readonly stream: Stream.Stream - readonly initialValue?: InitialA + readonly initialValue?: () => Effect.Effect readonly children: (latestValue: InitialA extends A ? Option.Some : Option.Option) => React.ReactNode }, ): React.ReactNode {