skip to Main Content

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.

  1. Without LauchEffect
Row {
        Text(text = "Hello World")
        Button(onClick = {
            state = !state
            Toast.makeText(context, "Button clicked", Toast.LENGTH_SHORT).show()
        }){
            Text(text = "Click me")
        }
    }
  1. 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


  1. https://developer.android.com/jetpack/compose/side-effects

    A side-effect is a change to the state of the app that happens outside the scope of a composable function.

    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).

    Login or Signup to reply.
  2. 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 a connected: Boolean parameter to indicate connection status. Now we can have a LaunchedEffect(connected) that will react to changes in connection status. Another important feature of LaunchedEffect 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search