From c1d5c37e605bfc5fa9d7460c65765a8a55c2d8fa Mon Sep 17 00:00:00 2001 From: Josep M Sobrepere Date: Thu, 2 Jul 2020 09:50:44 +0200 Subject: [PATCH] chore(shareReplay): ensure subscription is undefined after source completes --- src/internal/operators/shareReplay.ts | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/internal/operators/shareReplay.ts b/src/internal/operators/shareReplay.ts index c3bbe5d2f75..9fb5215af16 100644 --- a/src/internal/operators/shareReplay.ts +++ b/src/internal/operators/shareReplay.ts @@ -152,7 +152,6 @@ function shareReplayOperator({ let refCount = 0; let subscription: Subscription | undefined; let hasError = false; - let isComplete = false; return function shareReplayOperation(this: Subscriber, source: Observable) { refCount++; @@ -168,11 +167,16 @@ function shareReplayOperator({ subject!.error(err); }, complete() { - isComplete = true; subscription = undefined; subject!.complete(); }, }); + // The following condition is needed because source can complete synchronously + // upon subscription. When that happens `subscription` is first set to `undefined` + // and right after is set to the "closed subscription" returned by `subscribe` + if (subscription.closed && !hasError) { + subscription = undefined; + } } else { innerSub = subject.subscribe(this); } @@ -180,7 +184,7 @@ function shareReplayOperator({ this.add(() => { refCount--; innerSub.unsubscribe(); - if (subscription && !isComplete && useRefCount && refCount === 0) { + if (subscription && useRefCount && refCount === 0) { subscription.unsubscribe(); subscription = undefined; subject = undefined;