Date:

First and Last Operators in RxJS

The Raw `first` and `last` Operators: Picking the First and Last Emission

I recently came across MkDocs-Material by Martin Donath, a fantastic open-source project with over 22k GitHub stars.

It’s an incredible contribution to the community, making documentation hosting effortless.

While exploring it, I got curious about how such a large project achieves reactivity.

The stack is mostly HTML, SCSS, Preact, RxJS, and a few workers, and I saw this as the perfect opportunity to dive into RxJS—especially how it utilizes Observables and other advanced patterns.

The `first` Operator: Picking the First Emission

The `first` operator extracts only the very first value emitted by an observable and then completes.

Example:
import { of, first } from 'rxjs';

const numbers$ = of(-3, -2, -1, 0, 1, 2, 3);

numbers$.pipe(first()).subscribe(value => console.log(value));

// Output: -3

Applying Conditions

You can also pass a predicate function to `first`, which selects the first value that satisfies a condition:

import { of, first } from 'rxjs';

const numbers$ = of(-3, -2, -1, 0, 1, 2, 3);

numbers$.pipe(first(value => value > 0)).subscribe(value => console.log(value));

// Output: 1

The Raw `last` Operator: Picking the Last Emission

The `last` operator extracts only the last value emitted by an observable and then completes.

Example:
import { of, last } from 'rxjs';

const numbers$ = of(-3, -2, -1, 0, 1, 2, 3);

numbers$.pipe(last()).subscribe(value => console.log(value));

// Output: 3

Handling Errors with `catchError` and `retry`

Error handling is essential in reactive programming. The `catchError` operator allows graceful handling of errors, while `retry` lets you reattempt a failed observable sequence.

Example:
import { throwError, catchError, retry } from 'rxjs';

const faulty$ = throwError(() => new Error('Something went wrong!'));

faulty$.pipe(retry(2), catchError(err => of(`Error caught: ${err.message}`))).subscribe(value => console.log(value));

// Output: Error caught: Something went wrong!

Conclusion

The `first` and `last` operators are simple yet powerful tools for extracting key values from an observable stream.

Whether you’re handling API responses, processing user interactions, or managing error scenarios, these operators come in handy.

Mastering them, along with `forkJoin`, `catchError`, and `retry`, ensures you can build robust, efficient reactive applications.

FAQs

What is RxJS?

RxJS is a JavaScript library for reactive programming, developed by the creators of the popular JavaScript framework, Angular.

What is the `first` operator used for?

The `first` operator is used to extract the first value emitted by an observable and then complete.

What is the `last` operator used for?

The `last` operator is used to extract the last value emitted by an observable and then complete.

Latest stories

Read More

LEAVE A REPLY

Please enter your comment!
Please enter your name here