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

Cleanup polls on unsubscribeQueryResult #1933

Merged
merged 3 commits into from
Jan 22, 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
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,24 @@ export const build: SubMiddlewareBuilder = ({
timeout?: TimeoutId
pollingInterval: number
}> = {}

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)) {
msutkowski marked this conversation as resolved.
Show resolved Hide resolved
updatePollingInterval(action.payload, mwApi)
}
Expand Down Expand Up @@ -102,10 +116,7 @@ export const build: SubMiddlewareBuilder = ({
const currentPoll = currentPolls[queryCacheKey]
msutkowski marked this conversation as resolved.
Show resolved Hide resolved

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

Expand All @@ -116,10 +127,15 @@ export const build: SubMiddlewareBuilder = ({
}
}

function cleanupPollForKey(key: string) {
const existingPoll = currentPolls[key]
existingPoll?.timeout && clearTimeout(existingPoll.timeout)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please use an if statement here for readability.

delete currentPolls[key]
}

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