Observable atom does not get unsubscribed from if it never mount #3033
Unanswered
tien
asked this question in
Bug report
Replies: 2 comments 9 replies
-
It's a known limitation. That's why |
Beta Was this translation helpful? Give feedback.
6 replies
-
@dai-shi I ended up using this very limited implementation: import { atom, type Getter } from "jotai";
import { type Observable, firstValueFrom } from "rxjs";
type Data<T> = { value: T } | { error: unknown };
export function atomWithObservable<TValue>(
getObservable: (get: Getter) => Observable<TValue>,
) {
const valueAtom = atom((get) => {
const observable = getObservable(get);
const valueAtom = atom<Data<TValue | Promise<TValue>>>({
value: firstValueFrom(observable),
});
valueAtom.onMount = (update) => {
const subscription = observable.subscribe({
next: (value) => update({ value }),
error: (error) => update({ error }),
});
return () => {
subscription.unsubscribe();
};
};
return valueAtom;
});
return atom((get) => {
const data = get(get(valueAtom));
if ("error" in data) {
throw data.error;
}
return data.value;
});
} It creates 1 additional temporary subscription, always suspends initially, and only updates itself after mount. But it never leaks memory and works well enough for what I need. Do you think this is good enough to be added as a recipe to the Jotai docs? |
Beta Was this translation helpful? Give feedback.
3 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Bug Description
If the atom was started but never mounted, it will lead to a leaked subscription.
Reproduction Link
https://codesandbox.io/p/sandbox/clever-rubin-rsm38y
Beta Was this translation helpful? Give feedback.
All reactions