stoppableFlow

@ExperimentalCoroutinesApi
fun <T> stoppableFlow(block: suspend StoppableFlowCollector<T>.() -> Unit): Flow<T>

Creates a Flow with the ability to stop its collection early based on a custom condition.

Return

A new Flow with the ability to stop its collection early based on a custom condition.

Example usage:

stoppableFlow<Int> {
for (i in 1..10) {
if (i == 5) halt("Stopping at 5")
emit(i)
}
} // 1, 2, 3, 4

Parameters

block

A suspending lambda expression that takes a StoppableFlowCollector and defines the logic for collecting and emitting elements. To stop the collection early, call the halt method on the StoppableFlowCollector with a message describing the reason for stopping.