flowFromNonSuspend

fun <T> flowFromNonSuspend(function: () -> 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 flowFromSuspend for the suspend version.

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

Example of usage:

fun call(): R = ...
fun callAsFlow(): Flow<R> = flowFromNonSuspend(::call)

Another example:

var count = 0L
val flow = flowFromNonSuspend { count++ }

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

Output:

flowFromNonSuspend: 0
---
flowFromNonSuspend: 1
---
flowFromNonSuspend: 2

See also