@@ -21,6 +21,7 @@ import { ERROR_FACTORY, ErrorCode } from '../errors';
2121import { _FirebaseInstallationsInternal } from '@firebase/installations' ;
2222import { Storage } from '../storage/storage' ;
2323import { calculateBackoffMillis , FirebaseError } from '@firebase/util' ;
24+ import { VisibilityMonitor } from '../../../database/src/core/util/VisibilityMonitor' ;
2425
2526export class RealtimeHandler {
2627 constructor (
@@ -31,7 +32,9 @@ export class RealtimeHandler {
3132 private readonly projectId : string ,
3233 private readonly apiKey : string ,
3334 private readonly appId : string
34- ) { }
35+ ) {
36+ VisibilityMonitor . getInstance ( ) . on ( 'visible' , this . onVisibilityChange_ , this ) ;
37+ }
3538
3639 private streamController ?: AbortController ;
3740 private observers : Set < ConfigUpdateObserver > = new Set < ConfigUpdateObserver > ( ) ;
@@ -110,6 +113,15 @@ export class RealtimeHandler {
110113 return false ;
111114 }
112115
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+
113125 private resetRetryCount ( ) : void {
114126 this . retriesRemaining = ORIGINAL_RETRIES ;
115127 }
@@ -159,7 +171,6 @@ export class RealtimeHandler {
159171 'If-None-Match' : '*' ,
160172 'authentication-token' : installationTokenResult
161173 } ;
162-
163174 const url = this . getRealtimeUrl ( ) ;
164175 const requestBody = {
165176 project : this . projectId ,
@@ -257,4 +268,15 @@ export class RealtimeHandler {
257268 return new URL ( urlString ) ;
258269 }
259270
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+ }
260282}
0 commit comments