Android 在后续挂起方法调用之间发出LiveData以更新UI
当我从suspend方法调用中获得结果时,我正在尝试更新它们之间的UI。例如,下面是我的ViewModel类。方法a()、b()和c()是挂起方法Android 在后续挂起方法调用之间发出LiveData以更新UI,android,android-livedata,android-viewmodel,kotlin-coroutines,Android,Android Livedata,Android Viewmodel,Kotlin Coroutines,当我从suspend方法调用中获得结果时,我正在尝试更新它们之间的UI。例如,下面是我的ViewModel类。方法a()、b()和c()是挂起方法 class MainViewModel : ViewModel() { lateinit var userLiveData: LiveData<String> var repo = MainRepo() fun startTest() { userLiveData = liveData {
class MainViewModel : ViewModel() {
lateinit var userLiveData: LiveData<String>
var repo = MainRepo()
fun startTest() {
userLiveData = liveData {
var a = repo.a()
System.out.println("@@@@@@@@ $a")
emit(a)
var b = repo.b(a)
System.out.println("@@@@@@@@ $b")
emit(b)
var c = repo.c(b)
System.out.println("@@@@@@@@ $c")
emit(c)
}
}
}
和回购类
class MainRepo {
suspend fun a(): String{
delay(1000)
return "A"
}
suspend fun b(a: String): String{
delay(5000)
return a + "B"
}
suspend fun c(b: String): String{
return b + "-C"
}
}
我的问题是,在调用repo.a()
或repo.b()
或repo.c()
后,如何使用结果更新UI。
提前感谢。您可以通过使用协同程序的可变实时数据来实现这一点。 此外,挂起函数只能由协同程序或从另一个挂起函数调用。 我已经测试了下面的代码。希望这有帮助 您的viewModel:
val userLiveData = MutableLiveData<Map<String, String>>()
fun startTest() {
viewModelScope.launch {
var newVal = itemRepository.a()
userLiveData.value = mapOf("responseTime" to newVal)
newVal = itemRepository.b(newVal)
userLiveData.value = mapOf("downloadSpeed" to newVal)
newVal = itemRepository.c(newVal)
userLiveData.value = mapOf("uploadSpeed" to newVal)
}
}
回购:
输出:
setting textField Response as :A
setting textField2 Download Speed is :AB
setting textField3 Upload Speed is :AB-C
请检查答案。每次只更新一个TextView。我希望有3个文本视图并逐一更新。以speedtest为例,第一种方法将更新ping持续时间,第二种方法将更新下载速度文本视图,第三种方法将更新上传速度文本视图。好的。我已经更新了答案。也对它进行了测试。使用具有不同键的hashmap会有所帮助。创建新的映射实例有助于避免再次重置同一字段。此外,为了保持简单,您可以为每个文本字段使用单独的LiveData。但我个人更喜欢上面的答案。@Rookie嗨。你试过这个了吗?你认为这是正确的答案吗?
itemViewModel.userLiveData.observe(viewLifecycleOwner, Observer { result ->
result.get("responseTime")?.let {
println("setting textField Response as :" +result["responseTime"])
}
result.get("downloadSpeed")?.let {
println("setting textField2 Download Speed is :" +result["downloadSpeed"])
}
result.get("uploadSpeed")?.let {
println("setting textField3 Upload Speed is :" +result["uploadSpeed"])
}
})
itemViewModel.startTest()
class MainRepo {
suspend fun a(): String{
delay(1000)
return "A"
}
suspend fun b(a: String): String{
delay(5000)
return a + "B"
}
suspend fun c(b: String): String{
return b + "-C"
}
}
setting textField Response as :A
setting textField2 Download Speed is :AB
setting textField3 Upload Speed is :AB-C