Unsubscribe later with takeUntil if a condition is met

Viewed 578
1 Answers

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>

Related