flow

fun <T> flow(block: suspend FlowCollector<T>.() -> Unit): Flow<T>

Creates a cold flow from the given suspendable block. The flow being cold means that the block is called every time a terminal operator is applied to the resulting flow.

Example of usage:

fun fibonacci(): Flow<BigInteger> = flow {
var x = BigInteger.ZERO
var y = BigInteger.ONE
while (true) {
emit(x)
x = y.also {
y += x
}
}
}

fibonacci().take(100).collect { println(it) }

Emissions from flow builder are cancellable by default &mdash; each call to emit also calls ensureActive.

emit should happen strictly in the dispatchers of the block in order to preserve the flow context. For example, the following code will result in an IllegalStateException:

flow {
emit(1) // Ok
withContext(Dispatcher.IO) {
emit(2) // Will fail with ISE
}
}

If you want to switch the context of execution of a flow, use the flowOn operator.

Sources

common source
Link copied to clipboard