RXJS: How to use takeUntil until another Observable completes (and not emits)

Viewed 761

I have two Observables:

1: counts up a value and completes. (important: May complete before ever emitting any value!)

2: does stuff until 1 COMPLETES (not emits)

How would you implement this in RxJS?

My first try is using last() like:

firstObservable.pipe(
    takeUntil(secondObservable.pipe(last()))
  ).subscribe(count =>{
    //do stuff with count
  });

But the prroblem arises when firstObservable completes without ever emitting any value. An error is raised:

Error: no elements in sequence

Question: How can i use takeUntil (or any other operator) to stop the subscription after observable 2 completed and not throw an error when no last value ever was emitted?

1 Answers

You can use finalize on the secondOvservable and complete the firstObservable there. That way it does not depends on any value emitted, just on the complete event.

secondOvservable.pipe(
  finalize(() => firstObservable.complete())
).subscribe(count =>{
  //do stuff with count
});
Related