11import { DestroyRef , Injectable , Optional } from '@angular/core' ;
2- import { filter , race , take , timer } from 'rxjs' ;
2+ import { filter , lastValueFrom , race , Subject , take , timer } from 'rxjs' ;
33import { AppError } from 'xforge-common/exception-handling.service' ;
44import { FileService } from './file.service' ;
55import { DocSubscription , RealtimeDoc } from './models/realtime-doc' ;
@@ -36,6 +36,7 @@ export const noopDestroyRef: DestroyRef = {
3636} )
3737export class RealtimeService {
3838 protected readonly docs = new Map < string , RealtimeDoc > ( ) ;
39+ protected readonly disposingDocIds = new Map < string , Subject < void > > ( ) ;
3940 protected readonly subscribeQueries = new Map < string , Set < RealtimeQuery > > ( ) ;
4041
4142 constructor (
@@ -106,9 +107,9 @@ export class RealtimeService {
106107 let doc = this . docs . get ( key ) ;
107108
108109 // Handle documents that currently exist but are in the process of being disposed.
109- if ( doc ?. isDisposing ) {
110+ if ( doc != null && this . disposingDocIds . has ( doc . id ) ) {
110111 console . log ( `Waiting for document ${ key } to be disposed before recreating it.` ) ;
111- await doc . disposeCompleted ;
112+ await lastValueFrom ( this . disposingDocIds . get ( doc . id ) ! ) ;
112113 // Recursively call this method so if multiple callers are waiting for the same document to be disposed, they will
113114 // all get the same instance.
114115 return await this . get < T > ( collection , id , subscriber ) ;
@@ -127,7 +128,7 @@ export class RealtimeService {
127128 } ) ;
128129 }
129130 this . docs . set ( key , doc ) ;
130- this . docLifecycleMonitor . docCreated ( ` ${ collection } : ${ id } ` , subscriber . callerContext ) ;
131+ this . docLifecycleMonitor . docCreated ( getDocKey ( collection , id ) , subscriber . callerContext ) ;
131132 }
132133 doc . addSubscriber ( subscriber ) ;
133134
@@ -249,10 +250,24 @@ export class RealtimeService {
249250 }
250251 }
251252
253+ onDocDisposeStarted ( doc : RealtimeDoc ) : void {
254+ this . disposingDocIds . set ( doc . id , new Subject < void > ( ) ) ;
255+ this . docLifecycleMonitor . docDestroyed ( getDocKey ( doc . collection , doc . id ) ) ;
256+ this . docs . delete ( getDocKey ( doc . collection , doc . id ) ) ;
257+ }
258+
252259 async onLocalDocDispose ( doc : RealtimeDoc ) : Promise < void > {
253260 if ( this . isSet ( doc . collection , doc . id ) ) {
254261 await this . offlineStore . delete ( doc . collection , doc . id ) ;
255- this . docs . delete ( getDocKey ( doc . collection , doc . id ) ) ;
262+ }
263+ }
264+
265+ onDocDisposeFinished ( doc : RealtimeDoc ) : void {
266+ const disposingDocId = this . disposingDocIds . get ( doc . id ) ;
267+ if ( disposingDocId != null ) {
268+ disposingDocId . next ( ) ;
269+ disposingDocId . complete ( ) ;
270+ this . disposingDocIds . delete ( doc . id ) ;
256271 }
257272 }
258273
0 commit comments