Understanding stateful and stateless composable functions
In this section, I will show you the difference between stateful and stateless composable functions. To understand why this is important, let's first focus on the state term. In previous chapters, I described state as data that can change over time. Where the data is held (an SQLite database, a file, or a value inside an object) does not matter. What is important is that the UI must always show the current data. Therefore, if a value changes, the UI must be notified. To achieve this, we use observable types. This is not specific to Jetpack Compose, but a common pattern in many frameworks, programming languages, and platforms. For example, Kotlin supports observables through property delegates:
var counter by observable(-1) { _, oldValue, newValue -> println("$oldValue -> $newValue") } for (i in 0..3) counter = i
observable()
returns a delegate for a property that can be read and written...