[英]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()? using.observeAsState()时改变MutableLiveData的值后如何开始执行一段代码?
Example: MutableLiveData changes and after need to call Toast.示例:MutableLiveData 更改后需要调用 Toast。
This code returns error «Composable calls are not allowed inside the calculation parameter of inline fun remember(calculation: () -> TypeVariable(T)): TypeVariable(T)»此代码返回错误 «内联乐趣的计算参数内不允许可组合调用 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. remember{…}
中的块不是可组合的 scope,当您尝试将@Composable
function 放入 lambda 块或另一个不可组合的 function 时,您会遇到类似的问题。
I also don't think you need remember{…}
here anymore, since its already handled by your ViewModel
我也不认为你需要在这里
remember{…}
,因为它已经被你的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
在你的
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.您可以在 LaunchedEffect 内创建一个 Toast,即使有问题不可用我假设您尝试在 LaunchedEffect 内调用 LocalContext.current 这是不允许的,因为
LocalContext.current requires
来自 Composable scope 的调用。
What are differents between Composable function and normal function in Android? Android中的Composable function和normal function有什么区别?
@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()
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.