Skip to content

Commit

Permalink
refactor(shareReplay): avoid memory leaks (#5554)
Browse files Browse the repository at this point in the history
  • Loading branch information
josepot authored Aug 2, 2020
1 parent 373008a commit d9cfac3
Showing 1 changed file with 12 additions and 8 deletions.
20 changes: 12 additions & 8 deletions src/internal/operators/shareReplay.ts
Original file line number Diff line number Diff line change
Expand Up @@ -152,36 +152,40 @@ function shareReplayOperator<T>({
let subject: ReplaySubject<T> | undefined;
let refCount = 0;
let subscription: Subscription | undefined;
let hasError = false;
let isComplete = false;

return function shareReplayOperation(this: Subscriber<T>, source: Observable<T>) {
refCount++;
let innerSub: Subscription;
if (!subject || hasError) {
hasError = false;
if (!subject) {
subject = new ReplaySubject<T>(bufferSize, windowTime, scheduler);
innerSub = subject.subscribe(this);
subscription = source.subscribe({
next(value) { subject!.next(value); },
error(err) {
hasError = true;
subject!.error(err);
const dest = subject;
subscription = undefined;
subject = undefined;
dest!.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) {
subscription = undefined;
}
} else {
innerSub = subject.subscribe(this);
}

this.add(() => {
refCount--;
innerSub.unsubscribe();
if (subscription && !isComplete && useRefCount && refCount === 0) {
if (useRefCount && refCount === 0 && subscription) {
subscription.unsubscribe();
subscription = undefined;
subject = undefined;
Expand Down

0 comments on commit d9cfac3

Please sign in to comment.