diff --git a/src/internal/operators/shareReplay.ts b/src/internal/operators/shareReplay.ts index c3bbe5d2f75..635d2f93ba2 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;