From 4e756be08235d46683936f906e2901d2fea736fe Mon Sep 17 00:00:00 2001 From: Matt Hill Date: Mon, 19 Jul 2021 16:34:47 -0600 Subject: [PATCH] better unsubscribing --- client/lib/store.ts | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/client/lib/store.ts b/client/lib/store.ts index c667fc0..126b16e 100644 --- a/client/lib/store.ts +++ b/client/lib/store.ts @@ -1,6 +1,5 @@ import { DBCache, Dump, Http, Revision, Update } from './types' import { BehaviorSubject, Observable } from 'rxjs' -import { finalize } from 'rxjs/operators' import { applyOperation, getValueByPointer, Operation } from './json-patch-lib' import BTree from 'sorted-btree' @@ -34,11 +33,8 @@ export class Store { const path = `/${args.join('/')}` if (!this.watchedNodes[path]) { this.watchedNodes[path] = new BehaviorSubject(getValueByPointer(this.cache.data, path)) - this.watchedNodes[path].pipe( - finalize(() => delete this.watchedNodes[path]), - ) } - return this.watchedNodes[path].asObservable() + return this.watchedNodes[path] } update (update: Update): void { @@ -134,14 +130,19 @@ export class Store { } private updateWatchedNodes (revisionPath: string) { + const kill = (path: string) => { + this.watchedNodes[path].complete() + delete this.watchedNodes[path] + } + Object.keys(this.watchedNodes).forEach(path => { + if (this.watchedNodes[path].observers.length === 0) return kill(path) + if (path.includes(revisionPath) || revisionPath.includes(path)) { const val = getValueByPointer(this.cache.data, path) - if (val !== undefined) { - this.watchedNodes[path].next(val) - } else { - this.watchedNodes[path].complete() - } + if (val === undefined) return kill(path) + + this.watchedNodes[path].next(val) } }) }