cake
cake•2w ago

🧵 I had a small recommendation for the

🧵 I had a small recommendation for the Android documentation. Thread.
1 Reply
cake
cakeOP•2w ago
Here is something from the documentation:
var workouts: List<String> by remember { mutableStateOf(listOf()) }
LaunchedEffect("onLaunch") {
client.subscribe<List<String>>("workouts:get").collect { result ->
result.onSuccess { receivedWorkouts ->
workouts = receivedWorkouts
}
}
}
var workouts: List<String> by remember { mutableStateOf(listOf()) }
LaunchedEffect("onLaunch") {
client.subscribe<List<String>>("workouts:get").collect { result ->
result.onSuccess { receivedWorkouts ->
workouts = receivedWorkouts
}
}
}
While it still technically works, it's confusing because you are using a String constnat. What you actually want is
LaunchedEffect(Unit) {
LaunchedEffect(Unit) {
I think whoever made the Android documentation probably wasn't extremely familiar with Compose. If you aren't passing any arguments / keys into LaunchedEffect, the convention is to use Unit as the key. Unit in Kotlin is the same thing as void in other languages. The Compose Compiler under the hood distinguishes each LaunchedEffect call (and every other composable call as well) positionally, not based on keys. i.e. This will work jsut fine, printing both statements:
LaunchedEffect(Unit) {
delay(1.seconds)
println("Test1")
}
LaunchedEffect(Unit) {
delay(1.seconds)
println("Test2")
}
LaunchedEffect(Unit) {
delay(1.seconds)
println("Test1")
}
LaunchedEffect(Unit) {
delay(1.seconds)
println("Test2")
}
If LaunchedEffects keys are changed, it will dispose of the old version, and start the new one. It's very similar to remember in that regard.

Did you find this page helpful?