RxJS: takeUntil ignores Subject event

In the below code example the intention was to block the event from second$ by emitting 1 to Subject mid$.

import { Subject, timer } from "rxjs";
import { switchMap, takeUntil, tap } from "rxjs/operators";

const first$ = timer(1000);
const second$ = timer(2000);

const mid$ = new Subject();

  tap(() => { 
  switchMap(() => second$.pipe(
    tap(() => console.log("MISSED!"))

mid$.subscribe(() => console.log("RECEIVED"));


But it doesn’t work for some reason as the console shows:


I.e. the event emission in line mid$.next(1); isn’t taken into account by takeUntil(mid$)

What is the logic here?

I noticed that if I replace line mid$.next(1); with timer(0).subscribe(() => mid$.next(1)); it works as expected, but I’d like to know what is the proper way to handle such cases in RxJS.

85 thoughts on “RxJS: takeUntil ignores Subject event”

Leave a Comment