Thiago
12/19/2024, 2:28 PMerror() in some Android devices.
I'm not expert in Derived State and not the code owner. But I'm curious about Compose Atomic operations related to Derived States. The reason to invoke error() is the SnapshotStateList empty.
Is Compose Runtime scheduling two Operations stack.clear() and stack += item and running in sequence or is the derivedStateOf cache that is not atomic updated?
import androidx.compose.runtime.toMutableStateList
public class ItemsManager<T>(items: List<T>) {
private val stack: SnapshotStateList<T> = items.toMutableStateList()
public val lastItemOrNull: T? by derivedStateOf {
stack.lastOrNull()
}
public val lastItem: T by derivedStateOf {
lastItemOrNull ?: error("expected one item at least")
}
public fun replaceAll(item: T) {
stack.clear()
stack += item
}
}
@Composable
fun something() {
val manager = remember { ItemsManager(items = listOf(1)) }
val last = manager.lastItem
Text(text = "$last is the last item")
Button(onClick = {
manager.replaceAll(4)
}) {
Text(text = "Replace All")
}
}Stylianos Gakis
12/19/2024, 3:25 PMSnapshot.withMutableState { change1(); change2() }Stylianos Gakis
12/19/2024, 3:26 PMThiago
12/19/2024, 4:24 PMSnapshotStateList using withMutableState to have an atomic operation?Stylianos Gakis
12/19/2024, 4:48 PMThiago
12/19/2024, 7:56 PMerror() trigger. Even using delay like:
public suspend fun replaceAll(item: T) {
Snapshot.withMutableSnapshot {
stack.clear()
delay(1_000)
stack += item
}
}Stylianos Gakis
12/19/2024, 7:59 PMThiago
12/19/2024, 8:03 PMDocs not recommend suspend block but I did just to test and worked.must not suspend ifblockis called from a suspend function.withMutableSnapshot