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

Creates a flow from the given suspendable block.

Example of usage:

fun fibonacci(): Flow<Long> = flow {
    var f1 = 1L
    var f2 = 1L
    repeat(100) {
        var tmp = f1
        f1 = f2
        f2 += tmp

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.