take(1) vs first()
Solution 1:
Operators first()
and take(1)
aren't the same.
The first()
operator takes an optional predicate
function and emits an error
notification when no value matched when the source completed.
For example this will emit an error:
import { EMPTY, range } from 'rxjs';
import { first, take } from 'rxjs/operators';
EMPTY.pipe(
first(),
).subscribe(console.log, err => console.log('Error', err));
... as well as this:
range(1, 5).pipe(
first(val => val > 6),
).subscribe(console.log, err => console.log('Error', err));
While this will match the first value emitted:
range(1, 5).pipe(
first(),
).subscribe(console.log, err => console.log('Error', err));
On the other hand take(1)
just takes the first value and completes. No further logic is involved.
range(1, 5).pipe(
take(1),
).subscribe(console.log, err => console.log('Error', err));
Then with empty source Observable it won't emit any error:
EMPTY.pipe(
take(1),
).subscribe(console.log, err => console.log('Error', err));
Jan 2019: Updated for RxJS 6
Solution 2:
Tip: Only use first()
if:
- You consider zero items emitted to be an error condition (eg. completing before emitting) AND if there’s a greater than 0% chance of error you handling it gracefully
- OR You know 100% that the source observable will emit 1+ items (so can never throw).
If there are zero emissions and you are not explicitly handling it (with catchError
) then that error will get propagated up, possibly cause an unexpected problem somewhere else and can be quite tricky to track down - especially if it's coming from an end user.
You're safer off using take(1)
for the most part provided that:
- You're OK with
take(1)
not emitting anything if the source completes without an emission. - You don't need to use an inline predicate (eg.
first(x => x > 10)
)
Note: You can use a predicate with take(1)
like this: .pipe( filter(x => x > 10), take(1) )
. There is no error with this if nothing is ever greater than 10.
What about single()
If you want to be even stricter, and disallow two emissions you can use single()
which errors if there are zero or 2+ emissions. Again you'd need to handle errors in that case.
Tip: Single
can occasionally be useful if you want to ensure your observable chain isn't doing extra work like calling an http service twice and emitting two observables. Adding single
to the end of the pipe will let you know if you made such a mistake. I'm using it in a 'task runner' where you pass in a task observable that should only emit one value, so I pass the response through single(), catchError()
to guarantee good behavior.
Why not always use first()
instead of take(1)
?
aka. How can first
potentially cause more errors?
If you have an observable that takes something from a service and then pipes it through first()
you should be fine most of the time. But if someone comes along to disable the service for whatever reason - and changes it to emit of(null)
or NEVER
then any downstream first()
operators would start throwing errors.
Now I realize that might be exactly what you want - hence why this is just a tip. The operator first
appealed to me because it sounded slightly less 'clumsy' than take(1)
but you need to be careful about handling errors if there's ever a chance of the source not emitting. Will entirely depend on what you're doing though.
If you have a default value (constant):
Consider also .pipe(defaultIfEmpty(42), first())
if you have a default value that should be used if nothing is emitted. This would of course not raise an error because first
would always receive a value.
Note that defaultIfEmpty
is only triggered if the stream is empty, not if the value of what is emitted is null
.