lookout.devlookout.dev
search
Share Knowledge
21

RxJS: Filter for first value that meets condition

Tuesday, October 27, 2020

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()
);
Brian Love

I am a software engineer and Google Developer Expert in Web Technologies and Angular with a passion for learning, writing, speaking, teaching and mentoring. I regularly speaks at conferences and meetups around the country, and co-authored "Why Angular for the Enterprise" for O'Reilly. When not coding, I enjoy skiing, hiking, and being in the outdoors. I started lookout.dev to break down the barriers of learning in public. Learning in public fosters growth - for ourselves and others.

Google Developers Expert

Have a question or comment?