Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(store): refactor batch priority #2875

Merged
merged 1 commit into from
Dec 19, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading