flowFromSuspend

fun <T> flowFromSuspend(function: suspend () -> T): Flow<T>(source)

Creates a cold flow that produces a single value from the given function. It calls function for each new FlowCollector.

This function is similar to RxJava's fromCallable. See also flowFromNonSuspend for the non-suspend version.

The returned Flow is cancellable and has the same behaviour as kotlinx.coroutines.flow.cancellable.

Example of usage:

suspend fun remoteCall(): R = ...
fun remoteCallFlow(): Flow<R> = flowFromSuspend(::remoteCall)

Another example:

var count = 0L
val flow = flowFromSuspend {
delay(count)
count++
}

flow.collect { println("flowFromSuspend: $it") }
println("---")
flow.collect { println("flowFromSuspend: $it") }
println("---")
flow.collect { println("flowFromSuspend: $it") }

Output:

flowFromSuspend: 0
---
flowFromSuspend: 1
---
flowFromSuspend: 2

See also