@@ -19,10 +19,30 @@ export const build: SubMiddlewareBuilder = ({
19
19
timeout ?: TimeoutId
20
20
pollingInterval : number
21
21
} > = { }
22
+
23
+ function cleanupPollForKey ( key : string ) {
24
+ const existingPoll = currentPolls [ key ]
25
+ existingPoll ?. timeout && clearTimeout ( existingPoll . timeout )
26
+ delete currentPolls [ key ]
27
+ }
28
+
22
29
return ( next ) =>
23
30
( action ) : any => {
24
31
const result = next ( action )
25
32
33
+ if ( api . internalActions . unsubscribeQueryResult . match ( action ) ) {
34
+ const { queryCacheKey } = action . payload
35
+ const existingSubscriptionCount = Object . keys (
36
+ mwApi . getState ( ) [ reducerPath ] . subscriptions [ queryCacheKey ] || { }
37
+ ) . length
38
+
39
+ // There are no other components subscribed and sharing a poll for this queryCacheKey, so we can
40
+ // safely remove it
41
+ if ( existingSubscriptionCount === 0 ) {
42
+ cleanupPollForKey ( queryCacheKey )
43
+ }
44
+ }
45
+
26
46
if ( api . internalActions . updateSubscriptionOptions . match ( action ) ) {
27
47
updatePollingInterval ( action . payload , mwApi )
28
48
}
@@ -102,10 +122,7 @@ export const build: SubMiddlewareBuilder = ({
102
122
const currentPoll = currentPolls [ queryCacheKey ]
103
123
104
124
if ( ! Number . isFinite ( lowestPollingInterval ) ) {
105
- if ( currentPoll ?. timeout ) {
106
- clearTimeout ( currentPoll . timeout )
107
- }
108
- delete currentPolls [ queryCacheKey ]
125
+ cleanupPollForKey ( queryCacheKey )
109
126
return
110
127
}
111
128
@@ -117,9 +134,8 @@ export const build: SubMiddlewareBuilder = ({
117
134
}
118
135
119
136
function clearPolls ( ) {
120
- for ( const [ key , poll ] of Object . entries ( currentPolls ) ) {
121
- if ( poll ?. timeout ) clearTimeout ( poll . timeout )
122
- delete currentPolls [ key ]
137
+ for ( const key of Object . keys ( currentPolls ) ) {
138
+ cleanupPollForKey ( key )
123
139
}
124
140
}
125
141
}
0 commit comments