Search code examples
androidkotlinandroid-jetpack-composecompose-recomposition

How to start executing a block of code after changing the value of MutableLiveData when using .observeAsState() in Jetpack Compose?


How to start executing a block of code after changing the value of MutableLiveData when using .observeAsState()?

Example: MutableLiveData changes and after need to call Toast.

This code returns error «Composable calls are not allowed inside the calculation parameter of inline fun remember(calculation: () -> TypeVariable(T)): TypeVariable(T)»

@Composable
fun TextInfo() {
    val isSuccess by remember { viewModel.isSuccess.observeAsState() }//var isSuccess = MutableLiveData<Boolean>() — in ViewModel

    LaunchedEffect(isSuccess) {
        Log.d("IS SUCCESS", "trues")
    }
}

Solution

  • The block inside remember{…} is not a composable scope, its a similar issue you'll have when your try to put a @Composable function inside a lambda block or another function which is not a composable.

    I also don't think you need remember{…} here anymore, since its already handled by your ViewModel

    val isSuccess by viewModel.isSuccess.observeAsState()
    
    LaunchedEffect(isSuccess) {
         if (isSuccess) {
             Log.d("IS SUCCESS", "trues")
         }     
    }
    

    I made some attempt on your code, changing it like this,

    val isSuccess by viewModel.isSuccess.observeAsState()
    
    Button(onClick = { viewModel.updateSuccess() }) {}
                
    LaunchedEffect(isSuccess) {
        if (isSuccess) {
            Log.e("IS_SUCCESS", "IS_SUCCESS? $isSuccess")
        }
        
    }
    

    and in your ViewModel

    fun updateSuccess() {
       isSuccess.value = isSuccess.value?.not()
    }
    

    everytime the button is clicked, it prints

    29568-29568 E/IS_SUCCESS: IS_SUCCESS? true
    29568-29568 E/IS_SUCCESS: IS_SUCCESS? true