Skip to content

Commit

Permalink
Cleanup polls on unsubscribeQueryResult
Browse files Browse the repository at this point in the history
  • Loading branch information
msutkowski committed Jan 17, 2022
1 parent 637b0ca commit f41db88
Showing 1 changed file with 23 additions and 7 deletions.
30 changes: 23 additions & 7 deletions packages/toolkit/src/query/core/buildMiddleware/polling.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,30 @@ export const build: SubMiddlewareBuilder = ({
timeout?: TimeoutId
pollingInterval: number
}> = {}

function cleanupPollForKey(key: string) {
const existingPoll = currentPolls[key]
existingPoll?.timeout && clearTimeout(existingPoll.timeout)
delete currentPolls[key]
}

return (next) =>
(action): any => {
const result = next(action)

if (api.internalActions.unsubscribeQueryResult.match(action)) {
const { queryCacheKey } = action.payload
const existingSubscriptionCount = Object.keys(
mwApi.getState()[reducerPath].subscriptions[queryCacheKey] || {}
).length

// There are no other components subscribed and sharing a poll for this queryCacheKey, so we can
// safely remove it
if (existingSubscriptionCount === 0) {
cleanupPollForKey(queryCacheKey)
}
}

if (api.internalActions.updateSubscriptionOptions.match(action)) {
updatePollingInterval(action.payload, mwApi)
}
Expand Down Expand Up @@ -102,10 +122,7 @@ export const build: SubMiddlewareBuilder = ({
const currentPoll = currentPolls[queryCacheKey]

if (!Number.isFinite(lowestPollingInterval)) {
if (currentPoll?.timeout) {
clearTimeout(currentPoll.timeout)
}
delete currentPolls[queryCacheKey]
cleanupPollForKey(queryCacheKey)
return
}

Expand All @@ -117,9 +134,8 @@ export const build: SubMiddlewareBuilder = ({
}

function clearPolls() {
for (const [key, poll] of Object.entries(currentPolls)) {
if (poll?.timeout) clearTimeout(poll.timeout)
delete currentPolls[key]
for (const key of Object.keys(currentPolls)) {
cleanupPollForKey(key)
}
}
}
Expand Down

0 comments on commit f41db88

Please sign in to comment.