-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
* next: nextSubscriber * package: export nextSubscriber, bump version * package: update scripts
- Loading branch information
Showing
4 changed files
with
56 additions
and
6 deletions.
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
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,27 @@ | ||
import { expect, test } from "vitest"; | ||
|
||
import { nextSubscriber } from "./next"; | ||
import { sleep } from "./promise"; | ||
import { SheetProxy } from "./proxy"; | ||
import { Sheet } from "./sheet"; | ||
|
||
test("nextSubscriber", async () => { | ||
const sheet = new Sheet(); | ||
const proxy = new SheetProxy(sheet); | ||
const cell = proxy.new(1, "init"); | ||
|
||
let f = 0; | ||
nextSubscriber(cell, (v) => { | ||
f = v; | ||
}); | ||
|
||
// we wait | ||
await sleep(10); | ||
expect(f).toBe(0); | ||
|
||
cell.set(2); | ||
expect(f).toBe(2); | ||
|
||
cell.set(3); | ||
expect(f).toBe(2); | ||
}); |
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,24 @@ | ||
import { AnyCell } from "./cell"; | ||
import { Unsubscriber } from "./types"; | ||
|
||
/** | ||
* nextSubscriber subscribes to get the next value of a cell. This is useful | ||
* when a cell is already defined, but we know it will be updated (e.g. for a | ||
* ValueCell) and we want that next value. | ||
*/ | ||
export const nextSubscriber = <V>( | ||
cell: AnyCell<V>, | ||
cb: (v: V) => void, | ||
_expectedCount = 2 | ||
) => { | ||
// biome-ignore lint/style/useConst: need reference | ||
let uns: Unsubscriber; | ||
let count = 0; | ||
uns = cell.subscribe((arg) => { | ||
count++; | ||
if (count !== _expectedCount) return; | ||
if (arg instanceof Error) throw arg; | ||
cb(arg); | ||
queueMicrotask(uns); | ||
}); | ||
}; |