Bites of Compose 7

All about side effect

Guowei Lv

6 minute read

Let’s talk about side effects in Compose. Situation 1 What will happen when the button is clicked? @Composable fun Test() { var flag by remember { mutableStateOf(false) } Column { Button(onClick = { flag = !flag }) { Text("change") } Text(flag.toString()) Log.d("test", "flag is $flag") } } Answer The Text on the screen will change, also there will be a log entry in logcat. This logging behaviour is something called a side-effect in compose world.

Bites of Compose 6

What is Modifier after all?

Guowei Lv

3 minute read

In previous post we talked about the companion object Modifier and how it’s implementing the interface Modifier. Now it is time to go deeper and see Modifier’s internals. Situation 1 What is Modifier after all? Answer Well, what if I tell you Modifier is just a binary tree data structure. Let’s dive into the source code to prove this. First let’s take a look at the class hierachy, we have 3 pieces: Modifier(interface), Element and CombinedModifier.

Bites of Compose 5

Learn Jetpack Compose one bite at a time

Guowei Lv

2 minute read

Let’s talk about Modifier. Situation 1 What is the simplest Modifier? Answer Modifier What is it? a class? an object? It is a companion object, which implements the Modifier interface. companion object : Modifier { override fun <R> foldIn(initial: R, operation: (R, Element) -> R): R = initial override fun <R> foldOut(initial: R, operation: (Element, R) -> R): R = initial override fun any(predicate: (Element) -> Boolean): Boolean = false override fun all(predicate: (Element) -> Boolean): Boolean = true override infix fun then(other: Modifier): Modifier = other override fun toString() = "Modifier" } The formal version is Modifier.

Bites of Compose 4

Learn Jetpack Compose one bite at a time

Guowei Lv

6 minute read

This time we are focusing on derivedStateOf and how it is different from remember. Let’s look at this simple example: Situation 1 What will happen when user clicks on the Text? @Composable private fun Situation1() { var name by remember { mutableStateOf("guowei") } val uppercase by remember { derivedStateOf { name.uppercase() } } Text(uppercase, modifier = Modifier.clickable { name = "hello" }) } Answer The text will change from “GUOWEI” to “HELLO”.

Bites of Compose 3

Learn Jetpack Compose one bite at a time

Guowei Lv

4 minute read

Let’s do a bit of recap first. (I highly suggest you go through previous post if not already done so) Situation 1 Will clicking the button trigger the recompose of UserPage? data class User(var name: String) class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val user1 = User("Guowei Lv") val user2 = User("Guowei Lv") var user = user1 setContent { var flag by remember { mutableStateOf(true) } Column { Text(text = "Flag is $flag") UserPage(user = user) Button(onClick = { flag = !