简体   繁体   中英

RxJS takeUntil doesn't unsubscribe

I want to unsubscribe in declarative style with "takeUntil" operator. But that's basically does't work. I can see console output anyway.

const unsubscribe = new Subject();

function printFoo() {
  of('foo')
    .pipe(takeUntil(unsubscribe))
    .subscribe(console.log) // Why I can see 'foo' in the  console?
}

function onDestroy() {
  unsubscribe.next();
  unsubscribe.complete();
}

onDestroy()
setTimeout(() => printFoo(), 200)

StaackBlitz:

https://stackblitz.com/edit/rxjs-svfkxg?file=index.ts

PS I expected that even unsubscribe.next() would be enough to unsubscribe, but even with unsubscribe.complete() it doesn't work.

You're calling onDestroy() before the chain with takeUntil is even created.

When you eventually call printFoo() the previous emissions to unsubscribe won't be re-emited and the Subject unsubscribe is already completed anyway so takeUntil in this case will never complete the chain.

Because the Subject emits before printFoo subscription.

After you subscribe there are no more Subject emittions.

You could use BehaviorSubject instead, since it holds the emitted values (the last emitted value):

const unsubscribe = new BehaviorSubject(false);

function printFoo() {
  of('foo')
    .pipe(takeUntil(unsubscribe.pipe(filter(value => !!value)))) // Don't unsub if it's false emitted
    .subscribe(console.log)
}
function onDestroy() {
  unsubscribe2.next(true); // Emit true to cancel subscription
}

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