Member-only story

How To Handle UI Events In Jetpack Compose

Ryan Michael Kay
6 min readMar 5, 2021

--

In this short and practicle article, we will talk about handling UI events, such as onClick events, by taking full advantage of the Kotlin’s Function Types and Sealed Classes.

If you have not already learned about what a composable is, consider reading this article which explains the fundamentals. In any case, the important thing to understand is that composables are functions, not classes!

This means that we have to take a different approach than typical OOP solutions, but I will keep things simple to learn and apply.

Cat interacting with phone.

How To Model UI Events With A Sealed Class

First, we must understand what is meant by UI Events and how to use a language feature which is perfect for modelling them: Sealed Classes.

I have described this same process for Java and Kotlin (with the old view system) before, so I will keep this brief.

The Process

For each part of the UI (assume for now we are talking about one single screen of an App, but you can adjust things accordingly), ask yourself this question: What are all the different ways which the user can interact with this it?

Let us take an example from my first app built fully in compose, Graph Sudoku:

Graph Sudoku screenshot in 4x4 puzzle mode

The sealed class I use to represent the UI interactions of this screen looks like this:

sealed class ActiveGameEvent {
data class OnInput(val input: Int) : ActiveGameEvent()
data class OnTileFocused(val x: Int,
val y: Int) : ActiveGameEvent()
object OnNewGameClicked : ActiveGameEvent()
object OnStart : ActiveGameEvent()
object OnStop : ActiveGameEvent()
}

To explain briefly:

  • OnInput represents when a user hits an input button (i.e. 0, 1, 2, 3, 4)

--

--

Ryan Michael Kay
Ryan Michael Kay

Written by Ryan Michael Kay

Self-taught software developer & student of computer science.

No responses yet

Write a response