Skip to content

Lab · Kotlin and Android App Development

Lab: a train app's loading screen with coroutines

Labbeginner· about 1.5 hours· 4 steps

The brief

You write the logic behind a train enquiry app's screen as a console program: a PNR check that waits for the "network", seat and meal data loaded at the same time, fares added off the main thread, a refresh you can cancel, and a live distance board driven by a Flow and a StateFlow.

Why it matters

Every Android screen that loads data uses these exact tools: suspend functions for network calls, async to load several things at once, withContext to keep heavy work off the main thread, cancellation when the user leaves, and StateFlow to hold what the screen shows.

Skills you practise

  • suspend functions and runBlocking
  • launch, join and async/await
  • withContext and Dispatchers.Default
  • cancelling a job
  • Flow, map, collect and MutableStateFlow

You need

  • A web browser with the Kotlin Playground (play.kotlinlang.org), which includes kotlinx.coroutines; or IntelliJ IDEA / Android Studio with the kotlinx-coroutines-core library added

What you will have at the end

TrainStatus.kt: a console version of a train app's screen logic using suspend functions, launch, async, withContext, cancellation, Flow and StateFlow.

How it is marked (rubric, 100 points)
Correct, repeatable outputEvery line matches, in the same order every run: the email after the booking, 1 s for both loads, exactly three refreshes.35
Right coroutine tool for each joblaunch for the side job, async for the parallel loads, withContext for CPU work, cancel for the refresh, StateFlow for the board.35
ExplainedYou can say why the order is fixed and why the two loads take 1 s, not 2.20
Readable codeSmall suspend functions with clear names; no Thread.sleep anywhere.10

0/4 steps done

Step 1 of 4

A suspend function for the PNR check

The program prints "Checking PNR...", then after a second the PNR status, then "Done".

A suspend function can pause (for example while waiting for the network) without blocking the thread. delay(1000) is a pretend network call that waits one second. Suspend functions can only be called from a coroutine or another suspend function; runBlocking in main starts a coroutine for a console program (in an Android app you would use viewModelScope instead).

The three lines always come out in this order: the code inside one coroutine runs top to bottom, and the second println waits for pnrStatus to return.

Run this on your machine, then paste the output below
$ Run TrainStatus.kt in the Kotlin Playground and paste the output
Your notes: TrainStatus.kt

Write down each command you ran. It goes into your project summary.