0
0
Kotlinprogramming~5 mins

Flow builder and collect in Kotlin

Choose your learning style9 modes available
Introduction

Flow builder helps create a stream of data that you can watch and react to. Collect lets you get each piece of data from that stream.

When you want to handle a series of values over time, like user clicks or sensor data.
When you need to process data that comes in chunks, like downloading a file in parts.
When you want to update your app UI as new data arrives without blocking the main thread.
Syntax
Kotlin
val flow = flow {
    emit(value) // send a value to the flow
}

flow.collect { value ->
    // handle each value here
}

flow {} is used to create a flow that emits values.

collect is a suspending function that receives each emitted value.

Examples
This flow emits three numbers one by one, and collect prints each.
Kotlin
val flow = flow {
    emit(1)
    emit(2)
    emit(3)
}

flow.collect { value ->
    println(value)
}
This flow emits multiples of 10 from 10 to 50, and collect prints each with a message.
Kotlin
val flow = flow {
    for (i in 1..5) {
        emit(i * 10)
    }
}

flow.collect { value ->
    println("Received: $value")
}
Sample Program

This program creates a flow that emits numbers 1 to 3. Then it collects and prints each number.

Kotlin
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.runBlocking

fun main() = runBlocking {
    val numbersFlow = flow {
        for (i in 1..3) {
            emit(i)
        }
    }

    numbersFlow.collect { number ->
        println("Number: $number")
    }
}
OutputSuccess
Important Notes

You must call collect inside a coroutine or suspend function.

Flow is cold, meaning it does not start emitting until you collect it.

Summary

Use flow {} to build a stream of data.

Use collect to receive and handle each emitted value.

Flows help manage data that arrives over time without blocking your app.