Skip to content

v7 finalize broken for multiplexed resource handling #6712

Description

@RohanHart

Describe the bug

The change to make finalize execute in the order they're defined in the pipeline (#5433) breaks resource handling when the resource is multiplexed and the downstream subscriptions have their own finalization logic which uses the multiplexed resource.

Expected behavior

Rather than return to the pre-7 behaviour and another breaking change this could be a config option to finalize or make the "block" the finalizer apples to explicit with some bracketing operator.

Reproduction code

import { Subject } from 'rxjs';
import { filter, finalize, share } from 'rxjs/operators';

let resource = console.log;

const source = new Subject<number>();
const multiplex = source.pipe(
  finalize(() => {
    resource('closed');
    resource = undefined;
  }),
  share( /* { resetOnRefCountZero: () => timer(0) } */ )
);

const client = (m: number) => {
  resource('start ' + m);
  return multiplex.pipe(
    filter((v) => v % m === 0),
    finalize(() => {
      resource('stop ' + m);
    }),
    share()
  );
};

const client1 = client(2);
const l1 = client1.subscribe(console.log);
const l2 = client1.subscribe(console.log);

const l3 = client(3).subscribe(console.log);

source.next(2);
source.next(3);

l1.unsubscribe();

source.next(6);

l3.unsubscribe();

source.next(12);

l2.unsubscribe();

// Expected
//
// start 2
// start 3
// 2
// 2
// 3
// 6
// stop 3
// 12
// stop 2
// closed

// Actual
//
// start 2
// start 3
// 2
// 2
// 3
// 6
// stop 3
// 12
// closed
//
// throws: 1 errors occurred during unsubscription: TypeError: resource is not a function

Reproduction URL

https://stackblitz.com/edit/typescript-886qi6?file=index.ts

Version

7.4.0

Environment

No response

Additional context

This behaviour can be worked around by making the multiplexed observable's share reset asynchronously share({ resetOnRefCountZero: () => timer(0) }) but that's a bit obscure.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions