简体   繁体   English

using.observeAsState()时改变MutableLiveData的值后如何开始执行一段代码?

[英]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.

相关问题 在 Jetpack Compose 中使用 .observeAsState() 时,如何在更改 MutableLiveData 的值后开始执行一段代码? - How to start executing a block of code after changing the value of MutableLiveData when using .observeAsState() in Jetpack Compose? 使用 DataBinding 在 android 中调用 API 后,当 MutableLiveData 的 reposity 发生变化时,如何更新视图? - How can I update View when MutableLiveData change in reposity after call API in android using DataBinding? 使用 setOnClickListner 时如何重置 MutableLiveData 列表以显示新数据? - How to reset MutableLiveData list to display new data when using setOnClickListner? 直接访问时 MutableLiveData 值错误 - MutableLiveData wrong value when accessing directly 尝试使用 MutableLiveData 值时出现 NullPointerException - NullPointerException when trying to use MutableLiveData value Mockito 说使用 MutableLiveData 值时实际调用有不同的 arguments - Mockito Says Actual invocation has different arguments when using MutableLiveData Value 如何更改 ViewModel 中的 MutableLiveData 值 - How change MutableLiveData value inside ViewModel 如何观察何时返回 2 个 MutableLiveData 的值? - How to observe when values from 2 MutableLiveData are returned? 如何使用自定义对象绑定MutableLiveData? - How to binding MutableLiveData using Custom objects? 如何修复“必需的 MutableLiveData<String> 但“SwitchMap”被推断为 LiveData<Y> &quot; 当使用 Transformations.switchMap 时? - How to fix "Required MutableLiveData<String> but 'SwitchMap' was inferred to LiveData<Y>" when using Transformations.switchMap?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM