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

un example3() {
        val flowBuilder = flow {
            (1..5).forEach {
                emit(it)
                delay(500)
            }
        }

        runBlocking {
            val job=launch {
                flowBuilder.collect(::println)
            }

            delay(1100)
            job.cancel()
        }
    }

Example 2-2 and 2-3 Change context

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

 fun example2ChangeContextIncorrect() = runBlocking {
        val flow = flow {
            (1..10).forEach {
                withContext(Dispatchers.IO) {
                    delay(500)
                    emit(it)
                }
            }
        }

        flow.transform {
            val element = it
            withContext(Dispatchers.Main) {
                emit(element)
            }
        }

        flow.collect {
            println("collected $it on thread : ${Thread.currentThread()}")
        }
    }

Second example uses "flowOn" to change context

fun example2ChangeContextCorrect() = runBlocking {
        val flow = flow {
            (1..10).forEach {
                delay(500)
                println("emitted $it on thread : ${Thread.currentThread().name}")
                emit(it)
            }
        }.flowOn(Dispatchers.IO)

        val transformed = flow
            .transform {
                val element = it
                println("transformed $it on thread : ${Thread.currentThread().name}")
                emit(element)

            }//.flowOn(Dispatchers.Main)


        transformed
            .collect {
                println("collected $it on thread : ${Thread.currentThread().name}")
            }
    }

Last updated

Was this helpful?