Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(share): Prevent setup/reset race condition in share with refCount #7005

Merged
merged 2 commits into from Jul 8, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
16 changes: 15 additions & 1 deletion spec/operators/shareReplay-spec.ts
Expand Up @@ -2,7 +2,7 @@ import { expect } from 'chai';
import * as sinon from 'sinon';
import { shareReplay, mergeMapTo, retry, take } from 'rxjs/operators';
import { TestScheduler } from 'rxjs/testing';
import { Observable, Operator, Observer, of, from, defer, pipe } from 'rxjs';
import { Observable, Operator, Observer, of, from, defer, pipe, combineLatest, firstValueFrom, BehaviorSubject } from 'rxjs';
import { observableMatcher } from '../helpers/observableMatcher';

/** @test {shareReplay} */
Expand Down Expand Up @@ -274,6 +274,20 @@ describe('shareReplay', () => {
expect(subscriptions).to.equal(1);
});

it('should only subscribe once each with multiple synchronous subscriptions and unsubscriptions ', async () => {
// This may seem very specific, but it's a regression test for https://github.com/ReactiveX/rxjs/issues/6760

let subscriptions = 0;
const source = defer(() => {
++subscriptions;
// Needs to be an observable that doesn't complete
return new BehaviorSubject(1);
}).pipe(shareReplay({ bufferSize: 1, refCount: true }));

await firstValueFrom(combineLatest([source, source]));
expect(subscriptions).to.equal(1);
});

it('should default to refCount being false', () => {
testScheduler.run(({ cold, expectObservable, expectSubscriptions }) => {
const source = cold('a-b-c-d-e-f-g-h-i-j');
Expand Down
8 changes: 7 additions & 1 deletion src/internal/operators/share.ts
Expand Up @@ -211,7 +211,13 @@ export function share<T>(options: ShareConfig<T> = {}): MonoTypeOperatorFunction
// Basically, `subscriber === dest.subscribe(subscriber)` is `true`.
dest.subscribe(subscriber);

if (!connection) {
if (
!connection &&
// Check this shareReplay is still activate - it can be reset to 0
// and be "unsubscribed" _before_ it actually subscribes.
// If we were to subscribe then, it'd leak and get stuck.
refCount > 0
) {
// We need to create a subscriber here - rather than pass an observer and
// assign the returned subscription to connection - because it's possible
// for reentrant subscriptions to the shared observable to occur and in
Expand Down