From c42585f0c26f6f90b4196d010e01602f545d3fd7 Mon Sep 17 00:00:00 2001 From: ersimont <8042088+ersimont@users.noreply.github.com> Date: Sun, 1 Nov 2020 19:50:27 -0500 Subject: [PATCH] fix(app-state): unsubscribing mid-emit could sometimes result in an error --- projects/app-state/src/lib/store.spec.ts | 13 +++++++++++++ projects/app-state/src/lib/store.ts | 3 ++- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/projects/app-state/src/lib/store.spec.ts b/projects/app-state/src/lib/store.spec.ts index 59d1a0c9..706e6d96 100644 --- a/projects/app-state/src/lib/store.spec.ts +++ b/projects/app-state/src/lib/store.spec.ts @@ -157,6 +157,19 @@ describe('Store', () => { store('counter').set(1); expectSingleCallAndReset(spy, 1); }); + + it('works when the last subscriber to a child store unsubscribes mid-emit (production bug)', () => { + store('counter') + .$.pipe(skip(1)) + .subscribe(() => { + sub2.unsubscribe(); + }); + const sub2 = store('nested').$.subscribe(); + + expect(() => { + store('counter').set(1); + }).not.toThrowError(); + }); }); describe('()', () => { diff --git a/projects/app-state/src/lib/store.ts b/projects/app-state/src/lib/store.ts index 7bceea5b..64a46fce 100644 --- a/projects/app-state/src/lib/store.ts +++ b/projects/app-state/src/lib/store.ts @@ -160,7 +160,8 @@ export abstract class Store extends CallableObject> { } }); forOwn(this.activeChildren, (children) => { - for (const child of children) { + // `children` can be undefined if emitting from a previous key caused removed all subscribers to this key + for (const child of children || []) { child.maybeEmit(); } });