0
0
Android Kotlinmobile~5 mins

Flow basics in Android Kotlin

Choose your learning style9 modes available
Introduction

Flow helps you handle streams of data that change over time in your app. It lets you react to new data easily and smoothly.

When you want to listen to updates from a database and show them on screen.
When you need to handle user input events that come one after another.
When you want to fetch data from the internet and update the UI as data arrives.
When you want to combine multiple data sources and react to changes.
When you want to handle asynchronous tasks without blocking the app.
Syntax
Android Kotlin
val flow = flow {
  emit(value) // send a value to the flow
}

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

flow {} creates a stream of data.

emit() sends data to whoever is listening.

Examples
This flow emits three numbers one by one.
Android Kotlin
val numbers = flow {
  emit(1)
  emit(2)
  emit(3)
}
This collects the numbers and prints each one.
Android Kotlin
runBlocking {
  numbers.collect { number ->
    println(number)
  }
}
This creates a flow from fixed values without using emit.
Android Kotlin
val simpleFlow = flowOf("A", "B", "C")
Sample App

This program creates a flow that emits three strings. It collects and prints each string as it arrives.

Android Kotlin
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*

fun main() = runBlocking {
  val simpleFlow = flow {
    emit("Hello")
    emit("Flow")
    emit("World")
  }

  simpleFlow.collect { value ->
    println("Received: $value")
  }
}
OutputSuccess
Important Notes

Flows are cold, meaning they start emitting only when collected.

Use collect inside a coroutine to receive data.

Flows help keep your app responsive by handling data asynchronously.

Summary

Flow lets you work with streams of data that change over time.

You create flows with flow {} and send data with emit().

Collect data from flows using collect inside coroutines.