Skip to content
Tutorials Center
My learning

Topics

Lesson 111 of 134 ยท Testing and Tooling

Kotlin on Android

A guided tour of Kotlin on Android: why Android is Kotlin-first, Jetpack Compose, the Activity lifecycle, ViewModel with StateFlow and coroutines, with runnable stand-ins.

Android is the largest place Kotlin runs. Google announced Kotlin support in 2017 and made Android Kotlin-first in 2019: new APIs, official samples and libraries such as Jetpack Compose, Coroutines integration and KTX extensions are designed for Kotlin, and often usable only from Kotlin. If your goal is to build Android apps, you will write Kotlin.

This lesson is a tour of the main ideas, not an Android course. Android code needs the Android SDK, an emulator or a device and Gradle, and none of that exists in the runner on this site. So real Android snippets are labelled read-only. To make the ideas tangible we build small runnable stand-ins: plain Kotlin programs that behave like the real thing, using only the standard library and kotlinx.coroutines (see Introduction to Coroutines). That is also how Android developers test their logic: the less your code depends on Android classes, the easier it is to run, and the more of it can be checked on a plain JVM.

What an Android app is made of

An app is a package of components that the system starts and stops. You do not call main(); the operating system creates your objects when needed and destroys them when memory is short or the user leaves. The common building blocks:

  • Activity: one screen entry point (today usually a single Activity hosting all screens).
  • Composable functions: the UI itself, written with Jetpack Compose.
  • ViewModel: holds screen state and survives configuration changes such as screen rotation.
  • Repository: loads and saves data (network, database) behind an interface.
  • Manifest (AndroidManifest.xml): declares components and permissions.
XML
<!-- read-only example: AndroidManifest.xml (needs the Android build) -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <uses-permission android:name="android.permission.INTERNET" />
    <application android:label="Notes">
        <activity android:name=".MainActivity" android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>
Kotlin
// read-only example: needs the Android SDK and the Compose plugin
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            NotesApp()
        }
    }
}

setContent { ... } takes a lambda: it is a trailing-lambda call, the same Kotlin you already know. Much of Android's modern style is Kotlin features used heavily: lambdas with receivers, extension functions (KTX), delegated properties (by viewModels(), by remember), sealed classes and coroutines.

Jetpack Compose: UI as a function of state

Older Android UI was built in XML layout files and then mutated from code: find a view, set its text, hide this, show that. State and screen could drift apart. Jetpack Compose replaces that with a simple idea: the UI is a function of the state. You write functions that describe what the screen looks like for the current data. When the data changes, Compose runs the affected functions again and updates the screen.

Real Compose (read-only):

Kotlin
// read-only example: needs the Compose library
@Composable
fun Counter() {
    var count by remember { mutableStateOf(0) }

    Column {
        Text("Clicked $count times")
        Button(onClick = { count++ }) {
            Text("Click me")
        }
    }
}

@Composable marks a function that emits UI; a compiler plugin rewrites it so Compose can track which state each function reads. mutableStateOf is state Compose observes; remember keeps it alive between re-runs; by is the property delegation from Delegation. Clicking the button changes count, so Compose re-executes Counter and the text updates. You never touch the Text yourself.

We can model the core idea in plain Kotlin: a small type-safe builder (see Type-Safe Builders and DSLs) that creates a tree of nodes, and a "render" that prints it. The function takes state in, returns a tree out, and re-running it with new state gives the new screen.

Kotlin A tiny UI-as-function-of-state model

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Look at what the counterScreen function does not do: it never says "hide the button". The if inside simply describes the screen for each state. Because the state is an immutable data class replaced via copy, every change is easy to see and to test: counterScreen(CounterState(3, true)) can be checked without a phone. Real Compose is much smarter than this stand-in (it re-runs only the functions whose state changed, and skips the rest), but the mental model is the same.

The lifecycle: your objects do not live forever

The Android system can destroy and recreate an Activity at any time. The classic case is rotation: the screen changes shape, so the system tears down the Activity and builds a new one. Variables inside the old Activity are gone. Beyond rotation, the system also pauses screens that go to the background and kills the app's process when it needs memory.

An Activity moves through a lifecycle: onCreate โ†’ onStart โ†’ onResume (visible and interactive) โ†’ onPause โ†’ onStop โ†’ onDestroy. This stand-in shows the order and what happens to data on rotation, and why a ViewModel exists:

Kotlin Rotation destroys the screen, not the ViewModel

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

After the "rotation", the typed text is gone but the taps are still there. That is the whole reason for the ViewModel: screen state that must not vanish when the screen is rebuilt belongs in an object that outlives the screen. (Small pieces like a text field's content are saved by the system for you in real apps; large data goes in the ViewModel; permanent data goes to a database.)

Lifecycle bugs are the classic Android mistake: a callback that fires after the screen is gone and touches a view that no longer exists, or a network request that keeps running for a screen nobody sees. The fix is always the same: tie work to the lifecycle so it is cancelled with it. Coroutines make that natural, as shown below.

Kotlin's null safety, lateinit and a classic crash

Android creates your Activity itself, so some fields cannot be set in a constructor. Two Kotlin tools appear constantly: lateinit var ("I promise to set this before I read it") and the safe-call operators. Break the promise and you get one of Android's most recognizable crashes, shown here with a plain class:

Kotlin lateinit read too early (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The run ends with Exception in thread "main" kotlin.UninitializedPropertyAccessException: lateinit property title has not been initialized. In an app this crashes the process. Prefer constructor parameters or by lazy where possible, and use ::title.isInitialized when you really must check. See Advanced Properties.

ViewModel, StateFlow and coroutines

Modern Android architecture combines three things you already know:

  1. A sealed interface that describes every state a screen can be in (loading, content, error).
  2. A StateFlow holding the current state, so the UI can observe it (see StateFlow and SharedFlow).
  3. A coroutine scope tied to the ViewModel (viewModelScope) that starts the work and is cancelled automatically when the ViewModel dies.

The real framework pieces are read-only; the structure is the same as in the runnable version that follows:

Kotlin
// read-only example: needs androidx.lifecycle and Compose
class NotesViewModel(private val repository: NotesRepository) : ViewModel() {
    private val _state = MutableStateFlow<NotesState>(NotesState.Loading)
    val state: StateFlow<NotesState> = _state.asStateFlow()

    init {
        viewModelScope.launch {
            _state.value = try {
                NotesState.Content(repository.loadNotes())
            } catch (e: IOException) {
                NotesState.Error("No connection")
            }
        }
    }
}

@Composable
fun NotesScreen(viewModel: NotesViewModel) {
    val state by viewModel.state.collectAsStateWithLifecycle()
    when (val s = state) {
        NotesState.Loading -> CircularProgressIndicator()
        is NotesState.Content -> NotesList(s.notes)
        is NotesState.Error -> Text(s.message)
    }
}

Here is the same shape using only kotlinx.coroutines. The scope plays the role of viewModelScope; a delay stands in for the network. A collector prints every state the UI would receive:

Kotlin ViewModel, sealed UI state and StateFlow

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The UI code is a plain when over a sealed interface, so the compiler guarantees that every state has a branch. If you add a fourth state later, every screen that handles states refuses to compile until you deal with it. This is the same pattern as in Sealed Classes and Interfaces.

Cancellation follows the lifecycle

Android's rule of thumb: do not leak work. When the user leaves a screen, anything started for it should stop. Structured concurrency gives you this for free if you start coroutines in the right scope (see Structured Concurrency). viewModelScope is cancelled when the ViewModel is cleared; lifecycleScope is cancelled when the Activity is destroyed. The stand-in:

Kotlin Clearing the scope cancels work in flight

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The request is abandoned the moment the scope is cancelled, with no flag checks and no callback juggling. Notice the rethrown CancellationException: swallowing it is a well-known bug that keeps cancelled work alive (see Cancellation and Timeouts).

Android also needs the dispatchers from Dispatchers and Context: Dispatchers.Main runs on the UI thread (the only thread allowed to touch views), and Dispatchers.IO is for disk and network. Blocking the main thread for more than a few seconds produces the "Application Not Responding" dialog.

A learning path

If Android is your goal, a sensible order is: finish the core language here (null safety, collections, lambdas, classes, coroutines); install Android Studio and build a Compose "hello world"; learn state hoisting and remember; add navigation, a ViewModel, Room (the database library) and Retrofit or Ktor for networking; then read about testing ViewModels with fake repositories (you have already seen the pattern in Test Doubles). Kotlin Multiplatform (next but one lesson) lets you share the non-UI layers with an iOS app.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the central idea of Jetpack Compose?

    Compose functions describe what the screen should look like for the given state. When the state changes, Compose runs them again.
  2. 2. Why does a ViewModel exist?

    The Activity is destroyed and recreated on rotation; the ViewModel outlives it, so loaded data and in-flight work are not lost.
  3. 3. What does viewModelScope give you?

    Work launched in the scope is tied to the ViewModel's lifetime, so it cannot leak after the screen is gone.
  4. 4. Why model a screen's possible states with a sealed interface?

    An exhaustive when over a sealed type turns a forgotten state into a compile error.
  5. 5. What does lateinit var title: String read before it was set throw?

    Kotlin throws UninitializedPropertyAccessException: lateinit property title has not been initialized, a clearer message than a plain NPE.

Summary

  • Android is Kotlin-first: new libraries such as Jetpack Compose are designed around Kotlin features (lambdas with receivers, delegation, coroutines).
  • The system creates and destroys your components; do not assume objects live forever, and keep screen state that must survive rotation in a ViewModel.
  • Compose builds the UI as a function of immutable state; model states with a sealed interface and handle them with an exhaustive when.
  • ViewModel + StateFlow + viewModelScope is the standard way to load data and publish state; cancelling the scope cancels the work.
  • Real Android code needs the SDK and Gradle, so keep logic in plain Kotlin classes that you can test on any JVM.
  • Avoid blocking the main thread and swallowing CancellationException.

Next: Kotlin on the Server