[英]How to start executing a block of code after changing the value of MutableLiveData when using .observeAsState()?
How to start executing a block of code after changing the value of MutableLiveData when using.observeAsState()? using.observeAsState()时改变MutableLiveData的值后如何开始执行一段代码?
Example: MutableLiveData changes and after need to call Toast.示例:MutableLiveData 更改后需要调用 Toast。
@Composable
fun TextInfo() {
val isSuccess by remember { viewModel.isSuccess.observeAsState() }//var isSuccess = MutableLiveData<Boolean>() — in ViewModel
LaunchedEffect(isSuccess) {
Log.d("IS SUCCESS", "trues")
}
}
Showing a Toast is a side effect, so you need to put it inside a LaunchedEffect.显示 Toast 是一种副作用,因此您需要将它放在 LaunchedEffect 中。 Make the LiveData state the key of the LaunchedEffect.将 LiveData state 设为 LaunchedEffect 的键。 This causes the side effect to only occur when this particular LiveData's value changes.这会导致仅当此特定 LiveData 的值更改时才会发生副作用。
val myDataState = remember { someLiveData.observeAsState() }
LaunchedEffect(myDataState) {
// show the toast
}
Read about it in the documentation here .在此处的文档中阅读相关信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.