https://kotlinlang.org logo
#compose
Title
# compose
t

theapache64

02/21/2022, 7:05 PM
[ SOLVED]: What’s 
key
 actually doing to slot table? 🤔 🧵
Copy code
@Composable
fun Test() {
    val list = remember { mutableStateListOf("Audi", "BMW") }
    Box {
        list.firstOrNull()?.let { item ->
            key(item) {
                val car = remember { Car(item) }
                println(car.name)
                LaunchedEffect(Unit) {
                    list.remove(item)
                }
            }
        }
    }
}

class Car(val name: String)
The above snippet would print ->
Audi, BMW
but If we remove the
key(item)
, It’ll only create one object and will print
Audi, Audi
I am curious what’s actually happening inside the slot table when we wrap our composable with
key
l

Leland Richardson [G]

02/21/2022, 7:33 PM
Did you actually attempt to write code like this for a real use case?
😅 1
👎 1
Key will not reuse the slots/state unless it matches the key, so without it, your launched effect only runs once
t

theapache64

02/21/2022, 8:22 PM
Did you actually attempt to write code like this for a real use case?
Nope 😄 I was just experimenting stuffs
Key will not reuse the slots/state unless it matches the key, so without it, your launched effect only runs once
Got it. but I was looking for a detailed explanation. Maybe am not asking it the right way. I’ll come back with a rephrased version 🏃
j

jim

02/22/2022, 5:15 PM
One of the things Compose does is to allow widgets to be reordered (eg. a sorted list) without losing the internal state of the child widgets.  In order to do this, we create "groups" [of child widgets] which can be moved around.  In order to know if a group is moved, the group needs to have some sort of identity, so we can know if it represents the same item as before (state should be preserved) or if it is a completely different item (state of the child widget should be discarded). The 
key
 creates a new movable group, and gives it an identity (the value passed into the first parameter of 
key
.  This identity is stored in the slot table, and is checked the next time the composable is re-executed to determine if the group has been added/deleted/reordered. Does that answer your question?
t

theapache64

02/22/2022, 5:18 PM
Yes. Absolutely. Thank you so much 👍