Search⌘ K
AI Features

Solution: Practice a Suspending Function Using Flow

Explore how to create and practice suspending functions using Kotlin Flow. This lesson helps you understand emitting values, launching coroutines, and managing delays to handle asynchronous data streams in an Android development context.

We'll cover the following...

Solution

The solution to the challenge is as follows.

fun getFlow(): Flow<String> = flow {
    repeat(3) {
        delay(1000)
        emit("User$it")
    }
}

suspend fun main() {
    withContext(newSingleThreadContext("main")) {
        launch {
            repeat(3) {
                delay(100)
                println("Processing on coroutine")
            }
        }

        val list = getFlow()
        list.collect { println(it) }
    }
}
Solution to the challenge

Explanation

Here is a line–by–line ...