Javatpoint Logo
Javatpoint Logo

RxJS first() Filtering Operator

RxJS first() operator is a filtering operator that emits only the first value or the first value that meets some specified condition emitted by the source observable.

The RxJS first() operator is generally used when you are only interested in the first item emitted by the source observable or the first item that meets some criteria. In this case, you can use this operator to filter the Observable.

Syntax:

Following is the syntax of the RxJS first() operator:

Or

Parameter Explanation

  • predicate: It specifies an optional function called with each item to test for condition matching. It is an optional argument. Its default value is undefined.
  • defaultValue: The default value is emitted in the case when no valid value was found on the source. It is also an optional argument. Its default value is undefined.

Return value

The RxJS first() operator's return value is an observable of the first item that meets the condition.

Note: -

In some cases, the first() operator is not implemented as a filtering operator that returns an Observable, but as a blocking function that returns a particular item at such time as the source Observable emits that item. In those cases, if you instead want a filtering operator, you should use Take(1) or ElementAt(0).

The first() operator emits an EmptyError to the Observer's error callback if the Observable completes before sending any next notification. To avoid this error, you should use take(1) instead of first() operator.

Let us see some examples of the RxJS first() operator to understand it clearly.

Example 1 (Emit first value from a given sequence)

Output:

After executing the above example, you will see the following result:

RxJS first() Filtering Operator

Example 2 (Emit first value to meet a specific condition)

Output:

After executing the above example, you will see the following result:

RxJS first() Filtering Operator

In the above example, you can see that it has emitted the value which has met the set condition.

Example 3 (Utilizing default value)

Output:

After executing the above example, you will see the following result:

RxJS first() Filtering Operator
Next TopicRxJS Operators





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA