Skip to content

Commit

Permalink
WIP Use queueMicrotask in autoBatchEnhancer
Browse files Browse the repository at this point in the history
  • Loading branch information
markerikson committed Sep 4, 2022
1 parent 420baff commit e3a3acf
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 11 deletions.
41 changes: 31 additions & 10 deletions packages/toolkit/src/autoBatchEnhancer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,33 @@ import type { StoreEnhancer } from 'redux'

export const autoBatch = 'ReduxToolkit_autoBatch'

// Copied from https://github.com/feross/queue-microtask
let promise: Promise<any>
const queueMicrotaskShim =
typeof queueMicrotask === 'function'
? queueMicrotask.bind(typeof window !== 'undefined' ? window : global)
: // reuse resolved promise, and allocate it lazily
(cb: () => void) =>
(promise || (promise = Promise.resolve())).then(cb).catch((err: any) =>
setTimeout(() => {
throw err
}, 0)
)

export const autoBatchEnhancer =
(batchTimeout: number = 0): StoreEnhancer =>
(): StoreEnhancer =>
(next) =>
(...args) => {
const store = next(...args)

let notifying = true
let nextNotification: NodeJS.Timeout | undefined = undefined
let notificationQueued = false
// let nextNotification: NodeJS.Timeout | undefined = undefined
const listeners = new Set<() => void>()
const notifyListeners = () => {
nextNotification = void listeners.forEach((l) => l())
//nextNotification = void
notificationQueued = false
listeners.forEach((l) => l())
}

return Object.assign({}, store, {
Expand All @@ -29,14 +45,19 @@ export const autoBatchEnhancer =
try {
notifying = !action?.meta?.[autoBatch]
if (notifying) {
if (nextNotification) {
nextNotification = void clearTimeout(nextNotification)
}
notificationQueued = false
// if (nextNotification) {
// nextNotification = void clearTimeout(nextNotification)
// }
} else {
nextNotification ||= setTimeout(
notifyListeners,
batchTimeout
) as any
if (!notificationQueued) {
notificationQueued = true
queueMicrotaskShim(notifyListeners)
}
// nextNotification ||= setTimeout(
// notifyListeners,
// batchTimeout
// ) as any
}
return store.dispatch(action)
} finally {
Expand Down
2 changes: 1 addition & 1 deletion packages/toolkit/src/query/tests/helpers.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ export function setupApiStore<
api.middleware,
...middleware
),
enhancers: (e) => e.concat(autoBatchEnhancer(0)),
enhancers: (e) => e.concat(autoBatchEnhancer()),
})

type StoreType = EnhancedStore<
Expand Down

0 comments on commit e3a3acf

Please sign in to comment.