Flow_Basic

FILE : com.wlodar.jug.flow.basics.FlowExample1

Example1-1 - first flow:

Start with import :

import kotlinx.coroutines.flow.collect

Flows are "cold" which mean nothing happens when you create them

//no coroutines needed for building flow
val staticFlow: Flow<Int> = listOf(1, 2, 3).asFlow()

Its only when you call "collect" actual action is triggered

//only for collect
runBlocking {
    staticFlow.collect {
        println(it)
    }
}

Example1-2 - control eklements emission:

val flowBuilder = flow {
    (1..5).forEach {
        emit(it)
        emit(it+100)
        println("------")
        delay(500)
    }
    emit(1000)
}

Example 1-3 - Cancellation

Example 2-2 and 2-3 Change context

First example shows how to do it incorrectly - result -> Runtime error

Second example uses "flowOn" to change context

Last updated

Was this helpful?