Skip to content

Commit

Permalink
fix(core): ensure takeUntilDestroyed unregisters onDestroy listener o…
Browse files Browse the repository at this point in the history
…n unsubscribe (#49901)

The takeUntilDestroyed must always remove the onDestroy listener,
in the teardown logic.

PR Close #49901
  • Loading branch information
skrtheboss authored and thePunderWoman committed Apr 19, 2023
1 parent 856a0ec commit c029c67
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
3 changes: 2 additions & 1 deletion packages/core/rxjs-interop/src/take_until_destroyed.ts
Expand Up @@ -27,7 +27,8 @@ export function takeUntilDestroyed<T>(destroyRef?: DestroyRef): MonoTypeOperator
}

const destroyed$ = new Observable<void>(observer => {
destroyRef!.onDestroy(observer.next.bind(observer));
const unregisterFn = destroyRef!.onDestroy(observer.next.bind(observer));
return unregisterFn;
});

return <T>(source: Observable<T>) => {
Expand Down
13 changes: 13 additions & 0 deletions packages/core/rxjs-interop/test/take_until_destroyed_spec.ts
Expand Up @@ -63,4 +63,17 @@ describe('takeUntilDestroyed', () => {
source$.next(2);
expect(last).toBe(1);
});

it('should unregister listener if observable is unsubscribed', () => {
const injector = Injector.create({providers: []}) as EnvironmentInjector;
const destroyRef = injector.get(DestroyRef);
const unregisterFn = jasmine.createSpy();
spyOn(destroyRef, 'onDestroy').and.returnValue(unregisterFn);

const subscription = new BehaviorSubject(0).pipe(takeUntilDestroyed(destroyRef)).subscribe();

subscription.unsubscribe();

expect(unregisterFn).toHaveBeenCalled();
});
});

0 comments on commit c029c67

Please sign in to comment.