BACK
Lessons10. EMPTY and throwError
Lessons · 10

10. EMPTY and throwError

Two special streams

Sometimes you need to return an Observable "with no useful data" — in a branch of a condition, say: "if things went this way, return nothing"; "if things went wrong, return an error." RxJS ships two ready-made sources for exactly that.

EMPTY — the empty stream

EMPTY is an Observable that's already built. It emits no values through next and completes immediately via complete.

EMPTY
// complete() — that's all

Handy when a function's signature requires an Observable but you have no data, and there was no error either.

throwError — the error stream

throwError(factory) creates a stream that fails with an error the moment you subscribe. factory is a function that returns the error object.

throwError(() => 'Boom')
// error('Boom') — that's all

Why pass a function rather than the error itself? So a new error object is created on every subscription — safer, and easier to debug.

Your task

  1. Subscribe to EMPTY. In the subscription object, give only a complete handler that logs 'Empty complete'.
  2. Replace Rx.EMPTY on failed$ with throwError(() => 'Boom').
  3. The error handler already logs Error: Boom — no need to change it.
  4. Expected output: Empty complete → Error: Boom.
Solution spoiler · click to reveal
const { EMPTY, throwError } = Rx;

EMPTY.subscribe({
  complete: () => console.log('Empty complete')
});

const failed$ = throwError(() => 'Boom');

failed$.subscribe({
  error: error => console.log('Error: ' + error)
});
script.ts // TypeScript
CONSOLE · Console output
Hit Run to see the result...