简体   繁体   中英

RxJS takeUntil before higher-order observable

I am using the takeUntil operator before higher-order observable:

import { of, Subject, fromEvent, interval } from "rxjs";
import { takeUntil, mergeMap } from "rxjs/operators";

const subject = new Subject();

const source = fromEvent(document.querySelector("h1"), "click");

fromEvent(document.querySelector("p"), "click").subscribe(() => {
  subject.next();
});

source
  .pipe(
    takeUntil(subject),
    mergeMap(() => interval(1000))
  )
  .subscribe(x => console.log(x));

But we this code, I have a memory leak, because it does not unsubscribe from the interval . I can move it to be at the end of the chain, but this is error-prone. Developers can easily make this mistake. Is there a way to keep it like this, for example, and unsubscribe from the interval ?

to put takeUntil as the latest operator of pipe is a normal thing as to write mergeMap or any other operator. When people put it as the first operator they should understand why they do it.

For example in stop-watch rxjs example takeUntil isn't the latest, because it should be in the middle to support new start clicks.

interval(1000).pipe(
  skipUntil(this.start),
  takeUntil(this.stop$),
  repeat(),
);

You can:

But of course people should understand purpose of the code the write:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM