2

I want to unsubscribe to an observable with takeUntil in any case where the number does not equal 5. If the number is 5 want to do something and unsubscribe later, but it does not work.

This is my stackblitz link: https://stackblitz.com/edit/angular-ivy-lpkzyf?file=src%2Fapp%2Fapp.component.ts

Thank you.

nfianfnuae
  • 21
  • 2

1 Answers1

5

The statement

I want to unsubscribe to an observable with takeUntil in any case where the number does not equal 5

isn't exactly clear.

If you wish to unsubscribe the observable when the emitted value is other than 5, you'd need to use takeWhile operator, not takeUntil.

Try the following

const { of, Subject } = rxjs;
const { takeUntil, takeWhile } = rxjs.operators;

const unsubscribe$ = new Subject();

of(1, 2, 3, 4, 5, 6).pipe(
  takeWhile(value => value === 5),
  takeUntil(unsubscribe$)
).subscribe({
  next: (num) => {
    console.log(num);
    console.log('something');
    unsubscribe$.next();
  },
  complete: () => console.log('Stream complete')
});
 <script src="https://unpkg.com/rxjs@6.6.7/bundles/rxjs.umd.min.js"></script> 

But this would close the stream immediately when 1 is emitted.

I think what you're looking for is to ignore the values other than 5. In that case you'd need to use the filter operator.

const { of, Subject } = rxjs;
const { filter, takeUntil } = rxjs.operators;

const unsubscribe$ = new Subject();

of(1, 2, 3, 4, 5, 6).pipe(
  filter(value => value === 5),
  takeUntil(unsubscribe$)
).subscribe({
  next: (num) => {
    console.log(num);
    console.log('something');
    unsubscribe$.next();
  },
  complete: () => console.log('Stream complete')
});
<script src="https://unpkg.com/rxjs@6.6.7/bundles/rxjs.umd.min.js"></script>
ruth
  • 29,535
  • 4
  • 30
  • 57