RxJS: Filter for first value that meets condition
Tuesday, October 27, 2020
RxJS: Filter for first value that meets condition
Are you using RxJS and need to get the first, and only, value that meets a condition?
While you may consider using the filter()
operator followed by either the take()
or first()
operator, what you may not know is that the first()
operator takes an optional predicate function.
For example, if I have an RxJS observable that emits either null
if a user is not authenticated or the User
object if authenticated, and I am only interested in getting the authenticated user. Here is what the code might look like:
user$ = this.userService.user$.pipe(
first(user => user !== null)
);
Nice and succinct.
Code Examples
use the first() operator's optional predicate function
activeTags = this.tags.pipe(
first(tags => tags && tags.length > 0)
);
combining filter() and first() operators is the long-form
activeTags = this.tags.pipe(
filter(tags => tags && tags.length > 0),
first()
);
Have a question or comment?