Learn Kotlin · 17/18

Kotlin Flows: Reactive Asynchronous Streams

7 min read

Welcome, intrepid coder, to the wonderful world of Kotlin Flows! If you've ever dealt with asynchronous data—fetching from a network, listening to a database, or handling user input—you know it can sometimes feel like trying to catch a waterfall in a teacup. This is where Flows come in to save the day, providing a powerful and structured way to handle streams of data.

The Problem Before Flows

Imagine you're building a weather app. You need to get the current temperature, but that involves a network request which takes time. In the old days, you might have used callbacks. This works, but for more complex scenarios, like getting the forecast for the next five days and then updating the UI, you can end up in "callback hell," a confusing mess of nested callbacks.

How Flows Solve This

Kotlin Flows offer a way to handle a sequence of values over time, asynchronously. Think of it as a river of data. You can have a source (the producer) that emits values into the river, and at the other end, a collector (the consumer) that gathers and uses these values. The beauty of Flows is that they are built on top of coroutines, making them lightweight and efficient.


Flow Basics: Emitting and Collecting Data 💧

This is where our journey begins, at the source of the river. We'll learn how to create a Flow and how to drink... I mean, collect from it.

Creating a Flow

The most common way to create a Flow is by using the flow builder. Inside the flow block, you can emit values using the emit function.

kotlin
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.delay

fun getNumbers(): Flow<Int> = flow {
    for (i in 1..5) {
        delay(500) // Simulate some work
        emit(i)
    }
}

In this example, getNumbers() returns a Flow that will emit the numbers 1 through 5, with a half-second delay between each emission.

🧠 Fun Fact: Flows are cold by default. This means the code inside the flow builder doesn't run until someone starts collecting the values. It's like a motion-activated light; it only turns on when there's movement. Each new collector starts the flow from the beginning.

Collecting a Flow

To get the values from a Flow, you need a terminal operator. The most basic one is collect. Since collect is a suspend function, it needs to be called from within a coroutine.

kotlin
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.runBlocking

fun main() = runBlocking {
    println("Let's start collecting...")
    getNumbers().collect { number ->
        println("Collected: $number")
    }
    println("...collection finished.")
}

Output:

vbnet
Let's start collecting...
Collected: 1
Collected: 2
Collected: 3
Collected: 4
Collected: 5
...collection finished.

And just like that, you've created your first Flow and collected its values!


Intermediate Operators: map, filter, and transform 🔧

Now that we have our river of data, let's learn how to build some dams and waterwheels to process it. Intermediate operators allow you to transform the data within a flow without actually starting the collection.

map: Transforming Each Value

The map operator is like a conversion station on your river. It takes each value, applies a function to it, and emits the result.

kotlin
import kotlinx.coroutines.flow.map

fun main() = runBlocking {
    getNumbers()
        .map { number -> "Number: $number" } // Convert Int to String
        .collect { message ->
            println(message)
        }
}

Output:

apache
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5

filter: Letting Only Certain Values Pass

The filter operator is like a gatekeeper. It only allows values that meet a certain condition to pass through.

kotlin
import kotlinx.coroutines.flow.filter

fun main() = runBlocking {
    getNumbers()
        .filter { number -> number % 2 != 0 } // Only let odd numbers through
        .collect { oddNumber ->
            println("Odd number: $oddNumber")
        }
}

Output:

apache
Odd number: 1
Odd number: 3
Odd number: 5

transform: The Power to Do More

The transform operator is the super-powered version of map. It allows you to emit any number of values for each incoming value, or even none at all.

kotlin
import kotlinx.coroutines.flow.transform

fun main() = runBlocking {
    getNumbers()
        .transform { number ->
            emit("Before number: $number")
            emit("The number is: $number")
            emit("After number: $number")
        }
        .collect { message ->
            println(message)
        }
}

Output:

vim
Before number: 1
The number is: 1
After number: 1
Before number: 2
The number is: 2
After number: 2
... and so on

Terminal Operators: collect, toList, and first 🏁

Terminal operators are what trigger the flow to start emitting values. We've already met collect, but let's introduce a couple of its friends.

toList: Gathering All Values into a List

Sometimes, you just want to wait for all the values to be emitted and then get them as a list. toList is perfect for that.

kotlin
import kotlinx.coroutines.flow.toList

fun main() = runBlocking {
    val numberList = getNumbers().toList()
    println("All numbers: $numberList")
}

Output:

less
All numbers: [1, 2, 3, 4, 5]

first: Grabbing the First Value

If you only care about the very first value that a Flow emits, first is your go-to operator.

kotlin
import kotlinx.coroutines.flow.first

fun main() = runBlocking {
    val firstNumber = getNumbers().first()
    println("The very first number is: $firstNumber")
}

Output:

applescript
The very first number is: 1

StateFlow and SharedFlow: Managing App State 🌡️

While regular Flows are great, they have a limitation: they are cold. In many applications, especially in Android development, you need a way to represent a state that can be observed by multiple parts of your app. This is where StateFlow and SharedFlow come in as "hot" flows. A hot flow is like a live radio broadcast; it's on air whether anyone is listening or not.

StateFlow: The State Holder

A StateFlow is a special kind of hot flow that holds a single value, representing a state. It's an observable state-holder that emits the current and new state updates to its collectors. It's particularly useful in Android ViewModels for managing UI state.

A key feature of StateFlow is that when a new collector starts observing, it immediately receives the current state.

kotlin
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.delay

fun main() = runBlocking {
    val _uiState = MutableStateFlow("Loading")
    val uiState = _uiState.asStateFlow() // Expose as a read-only StateFlow

    val job1 = launch {
        uiState.collect { state ->
            println("Collector 1 sees: $state")
        }
    }

    delay(1000)
    _uiState.value = "Content Loaded"

    delay(1000)
    val job2 = launch {
        uiState.collect { state ->
            println("Collector 2 sees: $state")
        }
    }

    delay(1000)
    job1.cancel()
    job2.cancel()
}

Output:

apache
Collector 1 sees: Loading
Collector 1 sees: Content Loaded
Collector 2 sees: Content Loaded

Notice how Collector 2 immediately gets the latest state ("Content Loaded") when it starts collecting.

SharedFlow: For Broadcasting Events

A SharedFlow is a more general-purpose hot flow. It can be used to broadcast events to multiple collectors. Unlike StateFlow, a SharedFlow doesn't necessarily have an initial value.

You can configure a SharedFlow to replay a certain number of the most recent emissions to new collectors.

kotlin
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.asSharedFlow

fun main() = runBlocking {
    val _events = MutableSharedFlow<String>()
    val events = _events.asSharedFlow()

    val job1 = launch {
        events.collect { event ->
            println("Collector 1 heard: $event")
        }
    }

    delay(500)
    _events.emit("Event 1")

    delay(500)
    val job2 = launch {
        events.collect { event ->
            println("Collector 2 heard: $event")
        }
    }

    delay(500)
    _events.emit("Event 2")

    delay(1000)
    job1.cancel()
    job2.cancel()
}

Output:

apache
Collector 1 heard: Event 1
Collector 1 heard: Event 2
Collector 2 heard: Event 2

In this case, Collector 2 only receives "Event 2" because it started collecting after "Event 1" was already emitted, and we didn't configure any replay.


📚 Extra Reading

Challenge

Task

You are working on an analytics pipeline for an e-commerce platform. Your goal is to process a stream of raw ProductViewEvent data. You need to create a Kotlin Flow that filters these events to find only those in the "Electronics" category, transforms them into a PromotionalItem format, and finally collects them into a list.

Requirements

  1. Define a data class ProductViewEvent with two String properties: productId and category.
  2. Define another data class PromotionalItem with two String properties: productId and message.
  3. Implement the getHighInterestElectronics function. This function should:
    • Create a cold Flow from the provided rawEvents list.
    • Use an intermediate operator to filter the flow, keeping only events where the category is "Electronics".
    • Use another intermediate operator to map the filtered ProductViewEvent objects to PromotionalItem objects. The message for each PromotionalItem must be formatted as: "Special offer on product [productId]!".
  4. In the main function, call getHighInterestElectronics and use a terminal operator to collect all the emitted PromotionalItem objects into a List.
  5. Print the resulting list to the console.

Expected result

Your code should execute and print a single line to the console. This line will contain the string representation of the final list of PromotionalItem objects that have been filtered and transformed from the original event stream.

Expected Console Output

routeros
Processing complete. Promotional items:
[PromotionalItem(productId=p101, message=Special offer on product p101!), PromotionalItem(productId=p102, message=Special offer on product p102!), PromotionalItem(productId=p103, message=Special offer on product p103!)]
kotlin

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.