Table of Contents

Class FirstOrDefault

Namespace
Bonsai.Reactive
Assembly
Bonsai.Core.dll

Represents an operator that returns the first element of an observable sequence, or a default value if no such element exists.

Marble diagram

If the sequence has no elements, FirstOrDefault will emit a default value before terminating successfully.

Tip

If you are interested in finding the first element that meets some criteria, consider using the Condition operator before FirstOrDefault.

Example

Use FirstOrDefault to retrieve the first element of a sequence or a default value if the sequence is empty.

FirstOrDefault Example

Alternative

Use Take to retrieve one or more elements from the start of the sequence.

Warning

There are subtle but important differences between using the FirstOrDefault operator and Take(1):

  • When the source sequence has no elements, Take(1) will complete successfully with no emitted values, while FirstOrDefault will emit a default value before terminating successfully.
  • When the source sequence emits the first element, Take(1) will immediately cancel the subscription to the source sequence before emitting the notification. FirstOrDefault, on the other hand, will emit the notification and only afterwards cancel the subscription to the source sequence.
public class FirstOrDefault : Combinator
Inheritance
FirstOrDefault
Inherited Members

Methods

Process<TSource>(IObservable<TSource>)

Returns the first element of an observable sequence, or a default value if no such element exists.