如何使用liveData协程 block
在官方文档
https://developer.android.google.cn/topic/libraries/architecture/coroutines#livedata
现在可以在 liveData block 中将 livedata 与协程一起使用
val user: LiveData<User> = liveData {
val data = database.loadUser() // loadUser is a suspend function.
emit(data)
}
当我尝试这样使用时
fun onLogin(v: View) {
liveData(context = Dispatchers.IO) {
val reqLogin = ReqLogin(account = account.value?:"", password = MD5(password.value?:""))
val data = HttpManager.service(MobileApi::class.java).loginSuspend(reqLogin)
emit(data.data!!)
}
}
block 中的代码未执行
搜索发现liveData
block 总是用于赋值
https://medium.com/androiddevelopers/viewmodels-and-livedata-patterns-antipatterns-21efaef74a54
如果想刷新实时数据值,可以使用类似的转换
LiveData<Repo> repo = Transformations.switchMap(repoIdLiveData, repoId -> {
if (repoId.isEmpty()) {
return AbsentLiveData.create();
}
return repository.loadRepo(repoId);
});
但是我该如何使用它 1. Activity onResume并从服务器刷新数据 2.一些点击事件触发请求并获取一些新数据来显示
在我的登录场景中,使用 viewModelScope 似乎更有用
fun onLogin(v: View) {
val reqLogin = ReqLogin(account = account.value ?: "", password = MD5(password.value ?: ""))
viewModelScope.launch {
val data = withContext(Dispatchers.IO) {
HttpManager.service(MobileApi::class.java).loginSuspend(reqLogin)
}
_userInfo.value = data.data!!
_isLogin.value = true
}
}
最佳答案
fun onLogin(v: View) {
liveData(context = Dispatchers.IO) {
val reqLogin = ReqLogin(account = account.value?:"", password = MD5(password.value?:""))
val data = HttpManager.service(MobileApi::class.java).loginSuspend(reqLogin)
emit(data.data!!)
}
}
代码块未执行,因为文档说明了
The code block starts executing when LiveData becomes active and is automatically canceled after a configurable timeout when the LiveData becomes inactive.
您应该通过观察它来使其活跃。
关于android-livedata - 如何使用liveData协程 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57109044/