Bird
Raised Fist0
Android Kotlinmobile~20 mins

Flow basics in Android Kotlin - Mini App: Build & Ship

Choose your learning style10 modes available
Build: Flow Counter Screen
This screen shows a number that updates every second using Kotlin Flow. It demonstrates how to collect and display data from a Flow in an Android app.
Target UI
---------------------
| Flow Counter      |
|-------------------|
| Current count: 0  |
|                   |
| (Updates every 1s)|
---------------------
Use a Kotlin Flow that emits an increasing integer every second starting from 0.
Collect the Flow in the UI and display the current count.
Update the displayed number automatically as the Flow emits new values.
Use a ViewModel to hold the Flow and expose it to the UI.
Use Jetpack Compose for the UI.
Starter Code
Android Kotlin
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewmodel.compose.viewModel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.delay

class MainActivity : ComponentActivity() {
  override fun onCreate(savedInstanceState: android.os.Bundle?) {
    super.onCreate(savedInstanceState)
    setContent {
      FlowCounterScreen()
    }
  }
}

class CounterViewModel : ViewModel() {
  val counterFlow: Flow<Int> = flow {
    // TODO: Emit increasing numbers every second
  }
}

@Composable
fun FlowCounterScreen(counterViewModel: CounterViewModel = viewModel()) {
  // TODO: Collect counterFlow and display the current count
  Text(text = "Current count: ?")
}
Task 1
Task 2
Solution
Android Kotlin
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewmodel.compose.viewModel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.delay

class MainActivity : ComponentActivity() {
  override fun onCreate(savedInstanceState: android.os.Bundle?) {
    super.onCreate(savedInstanceState)
    setContent {
      FlowCounterScreen()
    }
  }
}

class CounterViewModel : ViewModel() {
  val counterFlow: Flow<Int> = flow {
    var count = 0
    while(true) {
      emit(count)
      count++
      delay(1000L)
    }
  }
}

@Composable
fun FlowCounterScreen(counterViewModel: CounterViewModel = viewModel()) {
  val count by counterViewModel.counterFlow.collectAsState(initial = 0)
  Text(text = "Current count: $count")
}

We created a counterFlow in the CounterViewModel that emits an increasing integer every second using a while(true) loop with delay(1000L). In the Compose UI, we collect this flow as state using collectAsState with an initial value of 0. This way, the UI automatically updates the displayed count every second as new values are emitted from the flow.

This example shows the basics of Kotlin Flow: creating a flow, emitting values over time, and collecting them in the UI reactively.

Final Result
Completed Screen
---------------------
| Flow Counter      |
|-------------------|
| Current count: 5  |
|                   |
| (Updates every 1s)|
---------------------
The number after 'Current count:' increases by 1 every second automatically.
No user input is needed; the screen updates itself.
Stretch Goal
Add a button to pause and resume the counter updates.
💡 Hint
Use a MutableState<Boolean> in the ViewModel to control emitting values and collect it in the UI to toggle emission.

Practice

(1/5)
1. What is the primary purpose of a Flow in Kotlin?
easy
A. To represent a stream of data that can emit multiple values over time
B. To store a single immutable value
C. To create a user interface layout
D. To handle exceptions synchronously

Solution

  1. Step 1: Understand what Flow represents

    A Flow is designed to emit multiple values asynchronously over time, like a stream of data.
  2. Step 2: Compare options with Flow's purpose

    Only To represent a stream of data that can emit multiple values over time correctly describes Flow as a stream of data emitting multiple values over time.
  3. Final Answer:

    To represent a stream of data that can emit multiple values over time -> Option A
  4. Quick Check:

    Flow = stream of data [OK]
Hint: Flow emits multiple values over time, not just one [OK]
Common Mistakes:
  • Confusing Flow with a single value container like LiveData
  • Thinking Flow is for UI layout
  • Assuming Flow handles exceptions synchronously
2. Which of the following is the correct way to create a Flow that emits numbers 1 to 3?
easy
A. val flow = flow { emit(1); emit(2); emit(3) }
B. val flow = flowOf(1, 2, 3)
C. All of the above
D. val flow = listOf(1, 2, 3).asFlow()

Solution

  1. Step 1: Review Flow creation methods

    Kotlin provides multiple ways to create flows: using flow builder with emit, flowOf, and converting collections with asFlow().
  2. Step 2: Check each option

    val flow = flow { emit(1); emit(2); emit(3) } uses flow builder with emit calls, B uses flowOf, and C converts a list to flow. All are valid ways.
  3. Final Answer:

    All of the above -> Option C
  4. Quick Check:

    Multiple ways to create Flow = D [OK]
Hint: Remember flow, flowOf, and asFlow() all create flows [OK]
Common Mistakes:
  • Thinking only flow builder with emit works
  • Confusing flowOf with a list
  • Not knowing asFlow() converts collections
3. What will be printed by this code?
val flow = flow {
  emit(10)
  emit(20)
}

runBlocking {
  flow.collect { value -> println(value) }
}
medium
A. No output
B. 20 10
C. Only 10
D. 10 20

Solution

  1. Step 1: Understand flow emission order

    The flow emits 10 first, then 20 in order.
  2. Step 2: Collect prints emitted values in order

    Collect receives values in the same order they are emitted, so prints 10 then 20.
  3. Final Answer:

    10 20 -> Option D
  4. Quick Check:

    Flow emits in order = 10 20 [OK]
Hint: Flow emits values in order unless otherwise specified [OK]
Common Mistakes:
  • Assuming values print in reverse order
  • Expecting only first value to print
  • Forgetting to run collect inside coroutine
4. Identify the error in this code snippet:
val flow = flow {
  emit(1)
  emit(2)
}

flow.collect { println(it) }
medium
A. Missing coroutine scope to call collect
B. emit() cannot be called inside flow builder
C. collect should be replaced with collectLatest
D. No error, code is correct

Solution

  1. Step 1: Check how collect is called

    collect is a suspend function and must be called inside a coroutine or suspend function.
  2. Step 2: Analyze code context

    Here, collect is called directly without coroutine scope like runBlocking or launch, causing error.
  3. Final Answer:

    Missing coroutine scope to call collect -> Option A
  4. Quick Check:

    collect needs coroutine scope [OK]
Hint: Always call collect inside coroutine scope [OK]
Common Mistakes:
  • Calling collect outside coroutine
  • Thinking emit() is invalid inside flow
  • Confusing collect with collectLatest necessity
5. You want to create a Flow that emits numbers 1 to 5 but only collect even numbers. Which code correctly achieves this?
hard
A. val flow = flow { for (i in 1..5) emit(i) } runBlocking { flow.collect { if (it % 2 == 0) println(it) } }
B. All of the above
C. val flow = flow { for (i in 1..5) if (i % 2 == 0) emit(i) } runBlocking { flow.collect { println(it) } }
D. val flow = flowOf(1, 2, 3, 4, 5) runBlocking { flow.filter { it % 2 == 0 }.collect { println(it) } }

Solution

  1. Step 1: Analyze each code snippet

    val flow = flow { for (i in 1..5) emit(i) } runBlocking { flow.collect { if (it % 2 == 0) println(it) } } emits all numbers and filters during collect; C emits only even numbers directly; D uses filter operator before collect.
  2. Step 2: Confirm all produce only even numbers on collect

    All options print only even numbers 2 and 4 when collected.
  3. Final Answer:

    All of the above -> Option B
  4. Quick Check:

    Multiple ways to filter Flow = B [OK]
Hint: Filter before or during collect both work [OK]
Common Mistakes:
  • Thinking filter must be before collect only
  • Not realizing emit can be conditional
  • Forgetting to run collect inside coroutine
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard