Skip to content

Commit

Permalink
add optional initalValue argument to from helper (#2429)
Browse files Browse the repository at this point in the history
* add optional initalValue to `from` helper

* Create dull-bikes-reply.md

---------

Co-authored-by: Ryan Carniato <ryansolid@gmail.com>
  • Loading branch information
chris-kruining and ryansolid authored Feb 21, 2025
1 parent e897701 commit 86ae8a9
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 14 deletions.
5 changes: 5 additions & 0 deletions .changeset/dull-bikes-reply.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"solid-js": patch
---

add optional initalValue argument to `from` helper
30 changes: 16 additions & 14 deletions packages/solid/src/reactive/observable.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,18 +84,20 @@ export function observable<T>(input: Accessor<T>): Observable<T> {
};
}

export function from<T>(
producer:
| ((setter: Setter<T | undefined>) => () => void)
| { subscribe: (fn: (v: T) => void) => (() => void) | { unsubscribe: () => void } }
): Accessor<T | undefined> {
const [s, set] = createSignal<T | undefined>(undefined, { equals: false });
if ("subscribe" in producer) {
const unsub = producer.subscribe(v => set(() => v));
onCleanup(() => ("unsubscribe" in unsub ? unsub.unsubscribe() : unsub()));
} else {
const clean = producer(set);
onCleanup(clean);
}
return s;
type Producer<T> =
| ((setter: Setter<T>) => () => void)
| { subscribe: (fn: (v: T) => void) => (() => void) | { unsubscribe: () => void } };

export function from<T>(producer: Producer<T>, initalValue: T): Accessor<T>;
export function from<T>(producer: Producer<T|undefined>): Accessor<T|undefined>;
export function from<T>(producer: Producer<T|undefined>, initalValue: T|undefined = undefined): Accessor<T | undefined> {
const [s, set] = createSignal<T | undefined>(initalValue, { equals: false });
if ("subscribe" in producer) {
const unsub = producer.subscribe(v => set(() => v));
onCleanup(() => ("unsubscribe" in unsub ? unsub.unsubscribe() : unsub()));
} else {
const clean = producer(set);
onCleanup(clean);
}
return s;
}

0 comments on commit 86ae8a9

Please sign in to comment.