delayWhen method Null safety

Stream<T> delayWhen(
  1. Stream<void> itemDelaySelector(
    1. T value
    ),
  2. {Stream<void>? listenDelay}
)

Delays the emission of items from the source Stream by a given time span determined by the emissions of another Stream.

When the source emits a data element, the itemDelaySelector function is called with the data element as argument, and return a "duration" Stream. The source element is emitted on the output Stream only when the "duration" Stream emits a data or done event.

Optionally, delayWhen takes a second argument listenDelay. When listenDelay emits its first data or done event, the source Stream is listen to. If listenDelay is not provided, delayWhen will listen to the source Stream as soon as the output Stream is listen.

Interactive marble diagram

Example

Stream.fromIterable([1, 2, 3])
  .delayWhen((i) => Rx.timer(null, Duration(seconds: i)))
  .listen(print); // [after 1s] prints 1 [after 1s] prints 2 [after 1s] prints 3

Stream.fromIterable([1, 2, 3])
  .delayWhen(
     (i) => Rx.timer(null, Duration(seconds: i)),
     listenDelay: Rx.timer(null, Duration(seconds: 2)),
  )
  .listen(print); // [after 3s] prints 1 [after 1s] prints 2 [after 1s] prints 3

Implementation

Stream<T> delayWhen(
  Stream<void> Function(T value) itemDelaySelector, {
  Stream<void>? listenDelay,
}) =>
    transform(DelayWhenStreamTransformer(itemDelaySelector,
        listenDelay: listenDelay));