@@ -101,6 +101,14 @@ type DecodedEntitiesCache = Map<
101101
102102const decodedEntitiesCache : DecodedEntitiesCache = new Map ( ) ;
103103
104+ const documentChangeListener : {
105+ subscribedQueriesCount : number ;
106+ unsubscribe : undefined | ( ( ) => void ) ;
107+ } = {
108+ subscribedQueriesCount : 0 ,
109+ unsubscribe : undefined ,
110+ } ;
111+
104112export const subscribeToDocumentChanges = ( handle : DocHandle < DocumentContent > ) => {
105113 const onChange = ( { patches, doc } : { patches : Array < Patch > ; doc : DocumentContent } ) => {
106114 const changedEntities = new Set < string > ( ) ;
@@ -327,9 +335,16 @@ export function subscribeToFindMany<const S extends AnyNoContext>(
327335
328336 const unsubscribe = ( ) => {
329337 const query = decodedEntitiesCache . get ( typeName ) ?. queries . get ( queryKey ) ;
330- if ( ! query || ! query . listeners ) return ;
331- query . listeners = query . listeners . filter ( ( cachedListener ) => cachedListener !== listener ) ;
332- console . log ( 'unsubscribe query' , query . listeners ) ;
338+ if ( query ?. listeners ) {
339+ query . listeners = query . listeners . filter ( ( cachedListener ) => cachedListener !== listener ) ;
340+ console . log ( 'unsubscribe query' , query . listeners ) ;
341+ }
342+
343+ documentChangeListener . subscribedQueriesCount -- ;
344+ if ( documentChangeListener . subscribedQueriesCount === 0 ) {
345+ documentChangeListener . unsubscribe ?.( ) ;
346+ documentChangeListener . unsubscribe = undefined ;
347+ }
333348 } ;
334349
335350 const entities = findMany ( handle , type ) ;
@@ -375,6 +390,11 @@ export function subscribeToFindMany<const S extends AnyNoContext>(
375390 } ) ;
376391 }
377392
393+ if ( documentChangeListener . subscribedQueriesCount === 0 ) {
394+ documentChangeListener . unsubscribe = subscribeToDocumentChanges ( handle ) ;
395+ }
396+ documentChangeListener . subscribedQueriesCount ++ ;
397+
378398 return { listener, getEntities, unsubscribe } ;
379399}
380400
0 commit comments