sample

fun <T> Flow<T>.sample(periodMillis: Long): Flow<T>

Returns a flow that emits only the latest value emitted by the original flow during the given sampling period.

Example:

flow {
repeat(10) {
emit(it)
delay(110)
}
}.sample(200)

produces the following emissions

1, 3, 5, 7, 9

Note that the latest element is not emitted if it does not fit into the sampling window.


fun <T> Flow<T>.sample(period: Duration): Flow<T>

Returns a flow that emits only the latest value emitted by the original flow during the given sampling period.

Example:

flow {
repeat(10) {
emit(it)
delay(110.milliseconds)
}
}.sample(200.milliseconds)

produces the following emissions

1, 3, 5, 7, 9

Note that the latest element is not emitted if it does not fit into the sampling window.