DoOnFirstEvent<T> extension

An extension on Stream that allows performing an action on the first event.

The doOnFirst method executes the provided onFirst callback with the first event emitted by the stream, before yielding any events downstream.

This is useful for scenarios such as lazy initialization, logging, authentication, or resource allocation that should occur only once, just before processing the stream.

The onFirst callback can be asynchronous; the stream will pause until onFirst completes before passing the first event further.

Example

Stream<int>.fromIterable([1, 2, 3])
  .doOnFirst((event) async {
    print('First event is $event');
  })
  .listen(print); // Prints: First event is 1 \n 1 \n 2 \n 3

See also:

  • Stream.doOnData in rxdart, which allows reacting to every event.
on

Methods

doOnFirst(Future<void> onFirst(T event)) Stream<T>

Available on Stream<T>, provided by the DoOnFirstEvent extension

Invokes onFirst with the first event emitted by the stream before any events are yielded.