Skip to content

Commit

Permalink
refactor: batch priority (#2875)
Browse files Browse the repository at this point in the history
  • Loading branch information
dmaskasky authored Dec 19, 2024
1 parent 7e463d1 commit 51a742d
Showing 1 changed file with 13 additions and 15 deletions.
28 changes: 13 additions & 15 deletions src/vanilla/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,8 @@ const addDependency = <Value>(
// Batch
//

type BatchPriority = 'H' | 'M' | 'L'

type Batch = Readonly<{
/** Atom dependents map */
D: Map<AnyAtom, Set<AnyAtom>>
Expand All @@ -181,16 +183,12 @@ const createBatch = (): Batch => ({
L: new Set(),
})

const addBatchFuncHigh = (batch: Batch, fn: () => void) => {
batch.H.add(fn)
}

const addBatchFuncMedium = (batch: Batch, fn: () => void) => {
batch.M.add(fn)
}

const addBatchFuncLow = (batch: Batch, fn: () => void) => {
batch.L.add(fn)
const addBatchFunc = (
batch: Batch,
priority: BatchPriority,
fn: () => void,
) => {
batch[priority].add(fn)
}

const registerBatchAtom = (
Expand All @@ -200,8 +198,8 @@ const registerBatchAtom = (
) => {
if (!batch.D.has(atom)) {
batch.D.set(atom, new Set())
addBatchFuncMedium(batch, () => {
atomState.m?.l.forEach((listener) => addBatchFuncMedium(batch, listener))
addBatchFunc(batch, 'M', () => {
atomState.m?.l.forEach((listener) => addBatchFunc(batch, 'M', listener))
})
}
}
Expand Down Expand Up @@ -514,7 +512,7 @@ const buildStore = (

// Step 2: use the topSortedReversed atom list to recompute all affected atoms
// Track what's changed, so that we can short circuit when possible
addBatchFuncHigh(batch, () => {
addBatchFunc(batch, 'H', () => {
const changedAtoms = new Set<AnyAtom>([atom])
for (let i = topSortedReversed.length - 1; i >= 0; --i) {
const [a, aState, prevEpochNumber] = topSortedReversed[i]!
Expand Down Expand Up @@ -659,7 +657,7 @@ const buildStore = (
isSync = false
}
}
addBatchFuncLow(batch, () => {
addBatchFunc(batch, 'L', () => {
const onUnmount = createInvocationContext(batch, () =>
atomOnMount(atom, (...args) => setAtom(...args)),
)
Expand All @@ -685,7 +683,7 @@ const buildStore = (
// unmount self
const onUnmount = atomState.m.u
if (onUnmount) {
addBatchFuncLow(batch, () => onUnmount(batch))
addBatchFunc(batch, 'L', () => onUnmount(batch))
}
delete atomState.m
if (import.meta.env?.MODE !== 'production') {
Expand Down

0 comments on commit 51a742d

Please sign in to comment.