-
-
Notifications
You must be signed in to change notification settings - Fork 153
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(rstream): add atom dep, add fromAtom() & docs
- Loading branch information
1 parent
04c3d59
commit ca3994a
Showing
3 changed files
with
41 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
import { ReadonlyAtom } from "@thi.ng/atom/api"; | ||
import { Stream } from "../stream"; | ||
|
||
/** | ||
* Yields stream of value changes in given atom / cursor. | ||
* Attaches watch to atom and compares values with `===`. | ||
* If `emitFirst` is true (default), also emits atom's | ||
* current value when first subscriber attaches to stream. | ||
* | ||
* See: @thi.ng/atom | ||
* | ||
* ``` | ||
* db = new Atom({a: 23, b: 88}); | ||
* cursor = new Cursor(db, (s) => s.a, (s, x)=> ({...s, a: x})) | ||
* | ||
* rs.fromAtom(cursor).subscribe(rs.trace("cursor val:")) | ||
* // cursor val: 23 | ||
* | ||
* cursor.reset(42); | ||
* // cursor val: 42 | ||
* | ||
* db.reset({a: 66}) | ||
* // cursor val: 66 | ||
* ``` | ||
* | ||
* @param atom | ||
*/ | ||
export function fromAtom<T>(atom: ReadonlyAtom<T>, emitFirst = true): Stream<T> { | ||
return new Stream<T>((stream) => { | ||
atom.addWatch(stream.id, (_, prev, curr) => { | ||
if (curr !== prev) { | ||
stream.next(curr); | ||
} | ||
}); | ||
emitFirst && stream.next(atom.deref()); | ||
return () => atom.removeWatch(stream.id); | ||
}); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters