@@ -21,6 +21,7 @@ import { ERROR_FACTORY, ErrorCode } from '../errors';
21
21
import { _FirebaseInstallationsInternal } from '@firebase/installations' ;
22
22
import { Storage } from '../storage/storage' ;
23
23
import { calculateBackoffMillis , FirebaseError } from '@firebase/util' ;
24
+ import { VisibilityMonitor } from '../../../database/src/core/util/VisibilityMonitor' ;
24
25
25
26
export class RealtimeHandler {
26
27
constructor (
@@ -31,7 +32,9 @@ export class RealtimeHandler {
31
32
private readonly projectId : string ,
32
33
private readonly apiKey : string ,
33
34
private readonly appId : string
34
- ) { }
35
+ ) {
36
+ VisibilityMonitor . getInstance ( ) . on ( 'visible' , this . onVisibilityChange_ , this ) ;
37
+ }
35
38
36
39
private streamController ?: AbortController ;
37
40
private observers : Set < ConfigUpdateObserver > = new Set < ConfigUpdateObserver > ( ) ;
@@ -110,6 +113,15 @@ export class RealtimeHandler {
110
113
return false ;
111
114
}
112
115
116
+ private stopRealtime ( ) : void {
117
+ if ( this . scheduledConnectionTimeoutId ) {
118
+ clearTimeout ( this . scheduledConnectionTimeoutId ) ;
119
+ this . scheduledConnectionTimeoutId = undefined ;
120
+ }
121
+ this . streamController ?. abort ( ) ;
122
+ this . isConnectionActive = false ;
123
+ }
124
+
113
125
private resetRetryCount ( ) : void {
114
126
this . retriesRemaining = ORIGINAL_RETRIES ;
115
127
}
@@ -159,7 +171,6 @@ export class RealtimeHandler {
159
171
'If-None-Match' : '*' ,
160
172
'authentication-token' : installationTokenResult
161
173
} ;
162
-
163
174
const url = this . getRealtimeUrl ( ) ;
164
175
const requestBody = {
165
176
project : this . projectId ,
@@ -257,4 +268,15 @@ export class RealtimeHandler {
257
268
return new URL ( urlString ) ;
258
269
}
259
270
271
+ private onVisibilityChange_ ( visible : unknown ) {
272
+ const wasInBackground = this . isInBackground ;
273
+ this . isInBackground = ! visible ;
274
+ if ( wasInBackground !== this . isInBackground ) {
275
+ if ( this . isInBackground ) {
276
+ this . stopRealtime ( ) ;
277
+ } else {
278
+ this . beginRealtime ( ) ;
279
+ }
280
+ }
281
+ }
260
282
}
0 commit comments