New

🌊 Kotlin Flow Tutorial for Android: StateFlow vs SharedFlow

Learn cold flows and operators, then build a Study Topics screen with a StateFlow for state, a SharedFlow for one-time messages and a unit test.

Beginner ⏱️ ~40 minutes 🧰 Kotlin, Coroutines, Jetpack Compose, Lifecycle 2.11
← Android Track

What You'll Learn in This Kotlin Flow Tutorial

This Kotlin Flow tutorial starts with the basics, a flow that emits values over time, and ends with a real Android screen. You will build a Study Topics list with a search box, tick topics off as done and see a Snackbar each time you finish one. Screen state lives in a StateFlow, the Snackbar message travels through a SharedFlow, and a unit test proves the search works.

Kotlin flows in Android are how a ViewModel streams data to the UI. They replace most uses of LiveData in modern Compose apps. If you have seen MutableStateFlow in the ViewModel topic of our Android track, this lesson explains what it really does and when to pick something else.

Prerequisites

Kotlin Flow Basics, Then a Real Screen

1 A flow is a stream you collect

A Flow emits several values one after another, and a suspend function returns only one. You build one with the flow { } builder and send values with emit:

import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.runBlocking

fun countdown(from: Int): Flow<Int> = flow {
    for (i in from downTo 0) {
        delay(1_000)   // pretend this is slow work
        emit(i)
    }
}

fun main() = runBlocking {
    countdown(3).collect { value -> println("Tick $value") }
}

Two rules make flows easy to reason about. First, a flow like this is cold: nothing runs until you call collect, and every new collector starts the code from the top again. Second, collect is a suspend function, so it runs inside a coroutine, such as viewModelScope.launch on Android.

2 Transform it with operators

Operators such as map, filter and onEach return a new flow and do not run anything until it is collected. catch handles errors from upstream, and flowOn moves upstream work to another dispatcher:

countdown(10)
    .filter { it % 2 == 0 }          // keep even numbers
    .map { "$it seconds left" }       // turn Int into String
    .onEach { println("Debug: $it") } // side effect, value passes through
    .catch { e -> emit("Timer failed: ${e.message}") }
    .flowOn(Dispatchers.Default)      // run the code above off the main thread
    .collect { text -> println(text) }

To merge two flows into one, use combine. It emits a new value whenever either input changes, using the latest value of each. You will use it in the project below.

3 StateFlow vs SharedFlow

Cold flows are perfect for "load this data". A screen also needs hot flows, which exist on their own and can have many collectors at once. Kotlin gives you two:

StateFlowSharedFlow
Has a current valueYes, always (.value)No
Initial valueRequiredNot needed
New collector getsThe latest valueOnly the last replay values (0 by default)
Repeated equal valuesSkippedDelivered
Use it forScreen state: lists, loading, textEvents: messages, navigation

In short: StateFlow vs SharedFlow is "what the screen looks like now" against "something just happened". A Snackbar message in a StateFlow would show again after rotation, because the new UI reads the current value. In a SharedFlow with no replay it is delivered once to whoever is listening.

And StateFlow vs LiveData? Both hold a current value. StateFlow needs an initial value, works in plain Kotlin and has all the flow operators. LiveData stops observing automatically when the screen stops. With StateFlow you get the same safety from collectAsStateWithLifecycle(), which is why Google's Android docs recommend StateFlow for new Compose code.

4 Add the dependencies

A new Compose project already includes coroutines and ViewModel. Add the Lifecycle Compose libraries (2.11.1 is the latest stable Lifecycle release, as listed on Google's release page this month) and the coroutines test library in app/build.gradle.kts:

dependencies {
    // ...existing dependencies
    implementation("androidx.lifecycle:lifecycle-runtime-compose:2.11.1")   // collectAsStateWithLifecycle
    implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.11.1") // viewModel()

    testImplementation("junit:junit:4.13.2")
    testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.10.2")
}

If your project uses a version catalog, add the same coordinates to libs.versions.toml. Keep kotlinx-coroutines-test on the same version as the coroutines library your project already uses.

5 Write the ViewModel

The ViewModel keeps two private MutableStateFlows, the topic list and the search text, and combines them into one uiState. stateIn turns that combined cold flow into a StateFlow that all collectors share. Events go through a MutableSharedFlow.

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch

data class Topic(val id: Int, val name: String, val done: Boolean = false)

data class TopicsUiState(
    val topics: List<Topic> = emptyList(),
    val doneCount: Int = 0,
    val total: Int = 0
)

sealed interface TopicsEvent {
    data class ShowMessage(val text: String) : TopicsEvent
}

class TopicsViewModel : ViewModel() {

    private val allTopics = MutableStateFlow(
        listOf(
            Topic(1, "Kotlin basics"),
            Topic(2, "Coroutines"),
            Topic(3, "Flow"),
            Topic(4, "StateFlow"),
            Topic(5, "Compose state")
        )
    )
    private val query = MutableStateFlow("")

    val uiState: StateFlow<TopicsUiState> =
        combine(allTopics, query) { topics, q ->
            val shown = if (q.isBlank()) topics
                        else topics.filter { it.name.contains(q.trim(), ignoreCase = true) }
            TopicsUiState(
                topics = shown,
                doneCount = topics.count { it.done },
                total = topics.size
            )
        }.stateIn(
            scope = viewModelScope,
            started = SharingStarted.WhileSubscribed(5_000),
            initialValue = TopicsUiState()
        )

    private val _events = MutableSharedFlow<TopicsEvent>()
    val events: SharedFlow<TopicsEvent> = _events.asSharedFlow()

    fun onQueryChange(newQuery: String) {
        query.value = newQuery
    }

    fun toggle(id: Int) {
        allTopics.update { list ->
            list.map { if (it.id == id) it.copy(done = !it.done) else it }
        }
        val topic = allTopics.value.first { it.id == id }
        if (topic.done) {
            viewModelScope.launch {
                _events.emit(TopicsEvent.ShowMessage("Nice! ${topic.name} is done"))
            }
        }
    }
}

Three details worth noticing:

  • The mutable flows are private. The UI only sees read-only StateFlow and SharedFlow, so only the ViewModel can change state.
  • update { } changes a StateFlow safely even if two coroutines update it at the same time.
  • SharingStarted.WhileSubscribed(5_000) keeps the upstream running for 5 seconds after the last collector leaves. A rotation finishes well within that, so nothing restarts; leaving the screen for good stops the work.

6 Collect the flows in Compose

Use collectAsStateWithLifecycle() for state, and collect events in a LaunchedEffect. The search text itself stays in Compose state with rememberSaveable, so typing is never delayed by a flow; each change is passed to the ViewModel.

import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel

@Composable
fun TopicsScreen(viewModel: TopicsViewModel = viewModel()) {
    val state by viewModel.uiState.collectAsStateWithLifecycle()
    var search by rememberSaveable { mutableStateOf("") }
    val snackbarHostState = remember { SnackbarHostState() }

    LaunchedEffect(Unit) {
        viewModel.events.collect { event ->
            when (event) {
                is TopicsEvent.ShowMessage -> snackbarHostState.showSnackbar(event.text)
            }
        }
    }

    Scaffold(snackbarHost = { SnackbarHost(snackbarHostState) }) { padding ->
        Column(Modifier.padding(padding).padding(16.dp)) {
            OutlinedTextField(
                value = search,
                onValueChange = { search = it; viewModel.onQueryChange(it) },
                label = { Text("Search topics") },
                singleLine = true,
                modifier = Modifier.fillMaxWidth()
            )
            Text(
                "Done: ${state.doneCount} of ${state.total}",
                modifier = Modifier.padding(vertical = 8.dp)
            )
            LazyColumn {
                items(state.topics, key = { it.id }) { topic ->
                    Row(
                        Modifier
                            .fillMaxWidth()
                            .clickable { viewModel.toggle(topic.id) }
                            .padding(vertical = 8.dp),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Checkbox(checked = topic.done, onCheckedChange = { viewModel.toggle(topic.id) })
                        Text(topic.name)
                    }
                }
            }
        }
    }
}

Call TopicsScreen() from setContent { } in MainActivity and run the app. Type "flow" and the list shrinks to Flow and StateFlow. Tick a topic and a Snackbar appears once. Rotate the phone: the ticks stay (state) and the Snackbar does not come back (event).

Not using Compose? In a Fragment or Activity, collect inside lifecycleScope.launch { repeatOnLifecycle(Lifecycle.State.STARTED) { viewModel.uiState.collect { render(it) } } } for the same lifecycle safety.

7 Test the StateFlow

viewModelScope runs on Dispatchers.Main, which does not exist in a plain JVM test, so replace it with a test dispatcher. Because uiState uses WhileSubscribed, start a collector in backgroundScope so the flow is active, as Google's flow testing guide shows. Put this in app/src/test:

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.*
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test

@OptIn(ExperimentalCoroutinesApi::class)
class TopicsViewModelTest {

    @Before fun setUp() { Dispatchers.setMain(UnconfinedTestDispatcher()) }
    @After fun tearDown() { Dispatchers.resetMain() }

    @Test
    fun searchFiltersTopicsAndToggleCountsDone() = runTest {
        val viewModel = TopicsViewModel()
        backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) {
            viewModel.uiState.collect {}
        }

        viewModel.onQueryChange("flow")
        assertEquals(listOf("Flow", "StateFlow"), viewModel.uiState.value.topics.map { it.name })

        viewModel.toggle(3)
        assertEquals(1, viewModel.uiState.value.doneCount)
    }
}

Run it with the green arrow next to the class. The collector in backgroundScope is cancelled automatically when the test ends.

Practice Task

Extend the Study Topics screen on your own, then check yourself with the quiz below.

  1. Add a "Show only unfinished" switch. Keep it in a third MutableStateFlow<Boolean> and add it to combine.
  2. Emit a different TopicsEvent when all five topics are done, and show it as a Snackbar with an action.
  3. Replace the hard-coded list with a fake repository whose topics(): Flow<List<Topic>> adds a delay(500), and show a loading state until the first value arrives.
  4. Write a second test that toggles a topic twice and checks that doneCount goes back to 0.

Kotlin Flow Tutorial Quiz

Five quick questions on this tutorial.

Frequently Asked Questions

What is the difference between Flow and StateFlow in Kotlin?

A plain Flow is cold: its code runs again for every collector and only when someone collects. StateFlow is a hot flow that always holds one current value, replays it to new collectors and skips values equal to the previous one.

When should I use SharedFlow instead of StateFlow?

Use StateFlow for screen state that always has a value. Use SharedFlow for things that happen, such as one-time messages or navigation events, where there is no current value and you do not want a new collector to see an old event.

Is StateFlow better than LiveData?

For new Kotlin and Compose code, Google recommends StateFlow. It needs an initial value and works outside Android classes. LiveData is still supported and stops observing automatically with the lifecycle; with StateFlow you get the same safety by collecting with collectAsStateWithLifecycle or repeatOnLifecycle.

Why use SharingStarted.WhileSubscribed(5000) with stateIn?

It keeps the upstream flow running for 5 seconds after the last collector leaves. A screen rotation recreates the UI within that time, so the work does not restart, but if the user really leaves the screen the upstream stops and saves resources.

How do I test a StateFlow in a ViewModel?

Replace Dispatchers.Main with a test dispatcher, run the test with runTest, start a collector in backgroundScope so stateIn is active, then call ViewModel functions and assert on uiState.value.

Sources

APIs checked against the Android Developers and Kotlin documentation on November 28, 2026. Library versions change often; prefer the versions your Android Studio template suggests.

What to Try Next

Keep learning Android

The free Android track takes you from Kotlin basics to complete Compose apps with data, networking and navigation.

Back to the Android Track