First

emit only the first item (or the first item that meets some condition) emitted by an Observable

If you are only interested in the first item emitted by an Observable, or the first item that meets some criteria, you can filter the Observable with the First operator.

In some implementations, First 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 implementations, if you instead want a filtering operator, you may have better luck with Take(1) or ElementAt(0).

In some implementations there is also a Single operator. It behaves similarly to First except that it waits until the source Observable terminates in order to guarantee that it only emits a single item (otherwise, rather than emitting that item, it terminates with an error). You can use this to not only take the first item from the source Observable but to also guarantee that there was only one item.

See Also

Language-Specific Information:

In RxGroovy, this filtering operator is implemented as first, firstOrDefault, and takeFirst.

Somewhat confusingly, there are also BlockingObservable operators called first and firstOrDefault that block and then return items, rather than immediately returning Observables.

There are also several other operators that perform similar functions.

The Filtering Operators

first

To filter an Observable so that only its first emission is emitted, use the first operator with no parameters.

first

You can also pass a predicate function to first, in which case it will produce an Observable that emits only the first item from the source Observable that the predicate evaluates as true.

firstOrDefault

The firstOrDefault operator is similar to first, but you pass it a default item that it can emit if the source Observable fails to emit any items

firstOrDefault

firstOrDefault also has a variant to which you can pass a predicate function, so that its Observable will emit the first item from the source Observable that the predicate evaluates as true, or the default item if no items emitted by the source Observable pass the predicate.

takeFirst

The takeFirst operator behaves similarly to first, with the exception of how these operators behave wihen the source Observable emits no items that satisfy the predicate. In such a case, first will throw a NoSuchElementException while takeFirst will return an empty Observable (one that calls onCompleted but never calls onNext).

single

The single operator is similar to first, but throws a NoSuchElementException if the source Observable does not emit exactly one item before successfully completing.

single

single also has a version that accepts a predicate, and emits the sole item emitted by the source Observable that matches that predicate, or notifies of an exception if exactly one such item does not match.

singleOrDefault

As with firstOrDefault there is also a singleOrDefault that emits a default item if the source Observable is empty, although it will still notify of an error if the source Observable emits more than one item.

singleOrDefault

And there is also a version of singleOrDefault that takes a predicate function and emits the sole item from the source Observable that matches that predicate, if any; the default item if no such items match; and makes an error notification if multiple items match.

first, firstOrDefault, single, singleOrDefault, and takeFirst do not by default operate on any particular Scheduler.

The BlockingObservable Methods

The BlockingObservable methods do not transform an Observable into another, filtered Observable, but rather they break out of the Observable cascade, blocking until the Observable emits the desired item, and then return that item itself.

To turn an Observable into a BlockingObservable so that you can use these methods, you can use either the Observable.toBlocking or BlockingObservable.from methods.

first

To retrieve the first emission from a BlockingObservable, use the first method with no parameters.

first

You can also pass a predicate function to the first method to retrieve the first emission from a BlockingObservable that satisfies the predicate.

firstOrDefault

As with the filtering operators, the first method of BlockingObservable will throw a NoSuchElementException if there is no first element in the source BlockingObservable. To return a default item instead in such cases, use the firstOrDefault method.

firstOrDefault

And, as with first, there is a firstOrDefault variant that takes a predicate function as an argument and returns the first item from the source BlockingObservable that satisfies that predicate, or a default item instead if no satisfying item was emitted.

single

The single operator is similar to first, but throws a NoSuchElementException if the source Observable does not emit exactly one item before successfully completing.

single

single also has a version that accepts a predicate, and returns the sole item emitted by the source Observable that matches that predicate, or throws an exception if exactly one such item does not match.

singleOrDefault

As with firstOrDefault there is also a singleOrDefault that returns a default item if the source Observable is empty, although it will still throw an error if the source Observable emits more than one item.

singleOrDefault

And there is also a version of singleOrDefault that takes a predicate function and returns the sole item from the source Observable that matches that predicate, if any; the default item if no such items match; and throws an error if multiple items match.

next

The next operator blocks until the BlockingObservable emits another item, and then returns that item. You can call this function repeatedly to get successive items from the BlockingObservable, effectively iterating over its emissions in a blocking fashion.

The latest operator is similar, but rather than blocking to wait for the next emitted item, it immediately returns the most-recently-emitted item, and only blocks if the Observable has not yet emitted anything.

mostRecent

The mostRecent operator similarly allows you to iterate over the emissions of a BlockingObservable, but its Iterable always immediately returns a value: either a default item you provide (if the BlockingObservable has not yet emitted an item), or the latest item the BlockingObservable has emitted.

In RxJava, this filtering operator is implemented as first, firstOrDefault, and takeFirst.

Somewhat confusingly, there are also BlockingObservable operators called first and firstOrDefault that block and then return items, rather than immediately returning Observables.

There are also several other operators that perform similar functions.

The Filtering Operators

first

To filter an Observable so that only its first emission is emitted, use the first operator with no parameters.

Sample Code

Observable.just(1, 2, 3)
          .first()
          .subscribe(new Subscriber<Integer>() {
        @Override
        public void onNext(Integer item) {
            System.out.println("Next: " + item);
        }

        @Override
        public void onError(Throwable error) {
            System.err.println("Error: " + error.getMessage());
        }

        @Override
        public void onCompleted() {
            System.out.println("Sequence complete.");
        }
    });
Next: 1
Sequence complete.
first

You can also pass a predicate function to first, in which case it will produce an Observable that emits only the first item from the source Observable that the predicate evaluates as true.

firstOrDefault

The firstOrDefault operator is similar to first, but you pass it a default item that it can emit if the source Observable fails to emit any items

firstOrDefault

firstOrDefault also has a variant to which you can pass a predicate function, so that its Observable will emit the first item from the source Observable that the predicate evaluates as true, or the default item if no items emitted by the source Observable pass the predicate.

takeFirst

The takeFirst operator behaves similarly to first, with the exception of how these operators behave wihen the source Observable emits no items that satisfy the predicate. In such a case, first will throw a NoSuchElementException while takeFirst will return an empty Observable (one that calls onCompleted but never calls onNext).

single

The single operator is similar to first, but throws a NoSuchElementException if the source Observable does not emit exactly one item before successfully completing.

single

single also has a version that accepts a predicate, and emits the sole item emitted by the source Observable that matches that predicate, or notifies of an exception if exactly one such item does not match.

singleOrDefault

As with firstOrDefault there is also a singleOrDefault that emits a default item if the source Observable is empty, although it will still notify of an error if the source Observable emits more than one item.

singleOrDefault

And there is also a version of singleOrDefault that takes a predicate function and emits the sole item from the source Observable that matches that predicate, if any; the default item if no such items match; and makes an error notification if multiple items match.

first, firstOrDefault, single, singleOrDefault, and takeFirst do not by default operate on any particular Scheduler.

The BlockingObservable Methods

The BlockingObservable methods do not transform an Observable into another, filtered Observable, but rather they break out of the Observable cascade, blocking until the Observable emits the desired item, and then return that item itself.

To turn an Observable into a BlockingObservable so that you can use these methods, you can use either the Observable.toBlocking or BlockingObservable.from methods.

first

To retrieve the first emission from a BlockingObservable, use the first method with no parameters.

first

You can also pass a predicate function to the first method to retrieve the first emission from a BlockingObservable that satisfies the predicate.

firstOrDefault

As with the filtering operators, the first method of BlockingObservable will throw a NoSuchElementException if there is no first element in the source BlockingObservable. To return a default item instead in such cases, use the firstOrDefault method.

firstOrDefault

And, as with first, there is a firstOrDefault variant that takes a predicate function as an argument and retrieves the first item from the source BlockingObservable that satisfies that predicate, or a default item instead if no satisfying item was emitted.

single

The single operator is similar to first, but throws a NoSuchElementException if the source Observable does not emit exactly one item before successfully completing.

single

single also has a version that accepts a predicate, and returns the sole item emitted by the source Observable that matches that predicate, or throws an exception if exactly one such item does not match.

singleOrDefault

As with firstOrDefault there is also a singleOrDefault that returns a default item if the source Observable is empty, although it will still throw an error if the source Observable emits more than one item.

singleOrDefault

And there is also a version of singleOrDefault that takes a predicate function and returns the sole item from the source Observable that matches that predicate, if any; the default item if no such items match; and throws an error if multiple items match.

next

The next operator blocks until the BlockingObservable emits another item, and then returns that item. You can call this function repeatedly to get successive items from the BlockingObservable, effectively iterating over its emissions in a blocking fashion.

The latest operator is similar, but rather than blocking to wait for the next emitted item, it immediately returns the most-recently-emitted item, and only blocks if the Observable has not yet emitted anything.

mostRecent

The mostRecent operator similarly allows you to iterate over the emissions of a BlockingObservable, but its Iterable always immediately returns a value: either a default item you provide (if the BlockingObservable has not yet emitted an item), or the latest item the BlockingObservable has emitted.

first

RxJS implements the first operator. It optionally takes a predicate function as a parameter, in which case, rather than emitting the first item from the source Observable, the resulting Observable will emit the first item from the source Observable that satisfies the predicate.

The predicate function itself takes three arguments:

  1. the item from the source Observable to be, or not be, filtered
  2. the zero-based index of this item in the source Observable’s sequence
  3. the source Observable object

An optional third parameter (named defaultValue) allows you to choose an item that first will emit if the source Observable does not emit any items (or if it does not emit the nth item that it expected.

Sample Code

var source = Rx.Observable.range(0, 10)
    .first(function (x, idx, obs) { return x % 2 === 1; });

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
Next: 1
Completed

If the source Observable emits no items (or no items that match the predicate), first will terminate with a “Sequence contains no elements.onError notification.

single

The single operator is similar, except that it only emits its item once the source Observable successfully completes after emitting one item (or one item that matches the predicate). If it emits either no such items or more than one such item, single will terminate with an onError notitifcation (“Sequence contains no elements.”).

find

The find operator is much like first except that the predicate argument is mandatory, and it behaves differently if no item from the source Observable matches the predicate. While first will send an onError notification in such a case, find will instead emit an undefined item.

Sample Code

var array = [1,2,3,4];

var source = Rx.Observable.fromArray(array)
    .find(function (x, i, obs) {
        return x === 5;
    });

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
Next: undefined
Completed
findIndex

The findIndex operator is similar to find, except that instead of emitting the item that matches the predicate (or undefined), it emits the zero-based index of that item in the source Observable’s sequence (or -1).

Sample Code

var array = [1,2,3,4];

var source = Rx.Observable.fromArray(array)
    .findIndex(function (x, i, obs) {
        return x === 5;
    });

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
Next: -1
Completed

find, findIndex, and first are found in each of the following distributions:

  • rx.all.js
  • rx.all.compat.js
  • rx.aggregates.js

They each require one of the following distributions:

  • rx.js
  • rx.compat.js
  • rx.lite.js
  • rx.lite.compat.js