观察回调没有被Kotlin Coroutines流动和Livedata触发吗?
我是Android开发的新手,并试图从各种示例项目中了解Coroutines和 livedata
。当用户输入用户名和密码时,我目前已经设置了一个函数来调用我的API。但是,在按下1按钮后,该应用似乎堵塞了,我无法将另一个API调用好像卡在待处理过程中一样。
这是我第一个用大量想法制作的Android应用程序,所以请让我知道我在哪里犯了错误!
活动:
binding.bLogin.setOnClickListener {
val username = binding.etUsername.text.toString()
val password = binding.etPassword.text.toString()
viewModel.userClicked(username, password).observe(this, Observer {
it?.let { resource ->
when (resource.status) {
Status.SUCCESS -> {
print(resource.data)
}
Status.ERROR -> {
print(resource.message)
}
Status.LOADING -> {
// loader stuff
}
}
}
})
}
ViewModel:
fun userClicked(username: String, password: String) = liveData(dispatcherIO) {
viewModelScope.launch {
emit(Resource.loading(data = null))
try {
userRepository.login(username, password).apply {
emit(Resource.success(null))
}
} catch (exception: Exception) {
emit(Resource.error(exception.message ?: "Error Occurred!", data = null))
}
}
}
存储库:
@WorkerThread
suspend fun login(
username: String,
password: String
): Flow<Resource<String?>> {
return flow {
emit(Resource.loading(null))
api.login(LoginRequest(username, password)).apply {
this.onSuccessSuspend {
data?.let {
prefs.apiToken = it.key
emit(Resource.success(null))
}
}
}.onErrorSuspend {
emit(Resource.error(message(), null))
}.onExceptionSuspend {
emit(Resource.error(message(), null))
}
}.flowOn(dispatcherIO)
}
API:
suspend fun login(@Body request: LoginRequest): ApiResponse<Auth>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您无需在
livedata
建造者中启动coroutine,它已经是suppend
,因此您可以在此处调用suppend
功能:如果您想使用
使用
使用flow
您可以使用aslivedata
函数:但是我不建议将
livedata
和flow
流中混合。我建议仅使用Flow
。仅使用
flow
:删除
暂停
关键字从登录
repository 中的功能。lifecyclescope
docs。
You don't need to launch a coroutine in
liveData
builder, it is alreadysuspend
so you can callsuspend
functions there:If you want to use
LiveDate
withFlow
you can convertFlow
toLiveData
object usingasLiveData
function:But I wouldn't recommend to mix up
LiveData
andFlow
streams in the project. I suggest to use onlyFlow
.Using only
Flow
:Remove
suspend
keyword from thelogin
function inRepository
.lifecycleScope
docs.