I am learning jetpack-compose and I want to understand the need for side-effect API in the android jetpack-compose library.
I have learned little about the launch effect and written code with and without it to handle out-of-composable scope work.
For both the cases the code works the same way.
- Without LauchEffect
Row {
Text(text = "Hello World")
Button(onClick = {
state = !state
Toast.makeText(context, "Button clicked", Toast.LENGTH_SHORT).show()
}){
Text(text = "Click me")
}
}
- With LauchEffect
Row {
Text(text = "Hello World")
Button(onClick = {
state = !state
}){
Text(text = "Click me")
}
LaunchedEffect(key1 = state, block = {
Toast.makeText(context, "Button clicked", Toast.LENGTH_SHORT).show()
})
}
Please help me understand the side-effect API and why we need a robust example
2
Answers
https://developer.android.com/jetpack/compose/side-effects
onClick = { }
<<< this lambda is not a composable (it is outside the scope of the function).It doesn’t get recomposed.
So your onClick is a side-effect, both examples are the same (one is easier to read).
In your example there is not much difference. But
LaunchedEffect
allows us to react to events coming to our composable from outside. For example, lets say our composable have aconnected: Boolean
parameter to indicate connection status. Now we can have aLaunchedEffect(connected)
that will react to changes in connection status. Another important feature ofLaunchedEffect
is that it will cancel previous coroutine before launching a new one, so we don’t have to worry about launching multiple coroutines performing the same task.