LiveLoveApp logo

ThrowIfEmpty Operator

throwIfEmpty() Operator

The throwIfEmpty() operator will return an Observable that immediately emits an error notification if the source Observable emits a completion notification without any next notifications.

This can be helpful to know when an Observable that is expected to produce a value, and thus emit a next notification, and never does.

Example

import { Subject } from 'rxjs';
import { throwIfEmpty } from 'rxjs/operators';

const subject = new Subject();

subject.pipe(throwIfEmpty(() => new Error('nothing to see here'))).subscribe({
  error: (e) => console.error('observer', e),
  next: console.log,
  complete: () => console.log('complete')
});

subject.complete();

See example on codesandbox

Let's quickly review the code above:

  • First, we create a new Subject.
  • Then, we use the throwIfEmpty() operator. The errorFactory function returns an Error that will be the value immediately emitted by the error notification.
  • Next, we subscribe to the Observable and provide an Observer.
  • Finally, we invoke the complete() method on the Subject without ever emitting a next notification.