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

Batch RTKQ "subscribe on reject" actions, and improve cache collection timer handling #2599

Merged
merged 4 commits into from
Aug 15, 2022
Merged
Changes from 1 commit
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
41 changes: 30 additions & 11 deletions packages/toolkit/src/query/core/buildMiddleware/cacheCollection.ts
Original file line number Diff line number Diff line change
@@ -11,6 +11,16 @@ import type {

export type ReferenceCacheCollection = never

function isObjectEmpty(obj: Record<any, any>) {
// Apparently a for..in loop is faster than `Object.keys()` here:
// https://stackoverflow.com/a/59787784/62937
for (let k in obj) {
// If there is at least one key, it's not empty
return false
}
return true
}

declare module '../../endpointDefinitions' {
interface QueryExtraOptions<
TagTypes extends string,
@@ -38,6 +48,15 @@ export const THIRTY_TWO_BIT_MAX_TIMER_SECONDS = 2_147_483_647 / 1_000 - 1
export const build: SubMiddlewareBuilder = ({ reducerPath, api, context }) => {
const { removeQueryResult, unsubscribeQueryResult } = api.internalActions

function anySubscriptionsRemainingForKey(
queryCacheKey: string,
api: SubMiddlewareApi
) {
const subscriptions =
api.getState()[reducerPath].subscriptions[queryCacheKey]
return !!subscriptions && !isObjectEmpty(subscriptions)
}

return (mwApi) => {
const currentRemovalTimeouts: QueryStateMeta<TimeoutId> = {}

@@ -103,18 +122,18 @@ export const build: SubMiddlewareBuilder = ({ reducerPath, api, context }) => {
Math.min(keepUnusedDataFor, THIRTY_TWO_BIT_MAX_TIMER_SECONDS)
)

const currentTimeout = currentRemovalTimeouts[queryCacheKey]
if (currentTimeout) {
clearTimeout(currentTimeout)
}
currentRemovalTimeouts[queryCacheKey] = setTimeout(() => {
const subscriptions =
api.getState()[reducerPath].subscriptions[queryCacheKey]
if (!subscriptions || Object.keys(subscriptions).length === 0) {
api.dispatch(removeQueryResult({ queryCacheKey }))
if (!anySubscriptionsRemainingForKey(queryCacheKey, api)) {
const currentTimeout = currentRemovalTimeouts[queryCacheKey]
if (currentTimeout) {
clearTimeout(currentTimeout)
}
delete currentRemovalTimeouts![queryCacheKey]
}, finalKeepUnusedDataFor * 1000)
currentRemovalTimeouts[queryCacheKey] = setTimeout(() => {
if (!anySubscriptionsRemainingForKey(queryCacheKey, api)) {
api.dispatch(removeQueryResult({ queryCacheKey }))
}
delete currentRemovalTimeouts![queryCacheKey]
}, finalKeepUnusedDataFor * 1000)
}
}
}
}