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
- Subscribe to
EMPTY. In the subscription object, give only acompletehandler that logs'Empty complete'. - Replace
Rx.EMPTYonfailed$withthrowError(() => 'Boom'). - The error handler already logs
Error: Boom— no need to change it. - 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
CONSOLE · Console output
Hit Run to see the result...