简体   繁体   中英

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")
    }
}

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

You can create a Toast inside LaunchedEffect even though not available in question i assume you try to call LocalContext.current inside LaunchedEffect which is not allowed because LocalContext.current requires calls from Composable scope.

What are differents between Composable function and normal function in Android?

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

    LaunchedEffect(isSuccess) {
        if(isSuccess){
            Toast.makeText(context, "IS SUCCESS", "trues", Toast.LENGTH_SHORT).show()
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM