Search code examples
androidkotlinandroid-jetpack-compose

What I should add as a key to LaunchedEffect to be changeable?


So, I need to run some code inside a LaunchedEffect.

First I wanted to use a Boolean, but once I set it to true, the LaunchedEffect block wasn't triggered again. I tried to set the value to null, before I set it to true again, but it didn't work as well.

Now I simple set it to Int type, and if I increase the value by 1 every time, it works as expected.

I used like this:

    val boolState = remember {
        mutableStateOf<Boolean?>(null)
    }
    LaunchedEffect(key1 = boolState.value) {
        if(boolState.value == true){
            //Do something
        }
    }

So my question is, what should I use as a key, to be able to update any time?


Solution

  • In Jetpack Compose, the LaunchedEffect will only trigger when the key changes. If you want to trigger the effect every time regardless of the key, you need a strategy to ensure the key changes whenever you want the effect to re-run.

    Your approach with an Int works because the value changes every time, thus triggering the effect. However, if you prefer using a Boolean or need more control over when the LaunchedEffect triggers, do something like this:

    boolState.value = !boolState.value`val boolState = remember { 
       mutableStateOf(false)
    }    
    LaunchedEffect(key1 = boolState.value) {
            if (boolState.value) {
                // Do something
           }
    }`