From 4b5aceae1df582470f3c360c328a14a1ad6ebea6 Mon Sep 17 00:00:00 2001 From: texuf Date: Fri, 26 Jul 2024 12:29:09 -0700 Subject: [PATCH] update use observable to return unsub function (#471) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit and add a get value in case it’s usable going to use usSyncExternalStore https://github.com/facebook/react/blob/f7ee804c2270b451087a697d181ef9f421e23f33/packages/use-sync-external-store/src/useSyncExternalStoreShimClient.js#L30 docs https://react.dev/reference/react/useSyncExternalStore --- packages/react-sdk/src/useObservable.ts | 4 ++-- packages/sdk/src/observable/observable.ts | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/react-sdk/src/useObservable.ts b/packages/react-sdk/src/useObservable.ts index e2eb53b5b..0f189664d 100644 --- a/packages/react-sdk/src/useObservable.ts +++ b/packages/react-sdk/src/useObservable.ts @@ -81,10 +81,10 @@ export function useObservable( if (!observable) { return } - const subscription = observable.subscribe(onSubscribe, { + const unsub = observable.subscribe(onSubscribe, { fireImediately: opts?.fireImmediately, }) - return () => subscription.unsubscribe(onSubscribe) + return unsub }, [opts, observable, onSubscribe]) const data = useMemo(() => { diff --git a/packages/sdk/src/observable/observable.ts b/packages/sdk/src/observable/observable.ts index b951dc212..97a57cb6a 100644 --- a/packages/sdk/src/observable/observable.ts +++ b/packages/sdk/src/observable/observable.ts @@ -26,7 +26,7 @@ export class Observable { subscribe( subscriber: (newValue: T) => void, opts: { fireImediately?: boolean; once?: boolean; condition?: (value: T) => boolean } = {}, - ): this { + ): () => void { const sub = { id: this._nextId++, fn: subscriber, @@ -37,7 +37,7 @@ export class Observable { if (opts.fireImediately) { this._notify(sub, this.value) } - return this + return () => this.unsubscribe(subscriber) } when(