【发布时间】:2020-12-21 02:18:13
【问题描述】:
我有一个场景,我的代码必须发送一个 api 调用并继续其工作(其中包含另一个 api 调用),而无需等待第一次调用的结果。
现在我在我的视图模型中这样做
fun showItem(id:Int) {
launch{
repo.markItemRead(id)
}
launch {
try {
val item = repo.getItemById(id).getOrThrow
commands.postValue(ShowItemCommand(item))
} catch (t:Throwable) {
commands.postValue(ShowError(R.string.error_retrieve_item))
repo.logError(t)
}
}
}
这会调用具有这两个功能的存储库
suspend fun markItemRead(id) {
try {
service.markItemAsRead(id)
} catch(ignored:Throwable) {
}
}
suspend fun getItemById(id) : Result<ItemData> {
return try {
val response : ItemEntity = service.getItemById(id)
val item = response.toData()
Result.Success(item)
} catch (t:Throwable) {
Result.Failure(t)
}
}
如果存储库完成所有这些工作,我会更喜欢它,因为每次都必须跟随另一个。
不幸的是,当我尝试在我的存储库中做这样的事情时:
suspend fun getItemById(id:Int) : Result<ItemData> {
try {
service.markItemAsRead(id)
} catch(ignored:Throwable) {
}
return try {
val response : ItemEntity = service.getItemById(id)
val item = response.toData()
Result.Success(item)
} catch (t:Throwable) {
Result.Failure(t)
}
}
它会等待markItemAsRead 函数完成后再继续
除了定义存储库的范围并将markItemAsRead 调用放在launch 中(我已经读过在挂起函数中执行此操作是不正确的)之外,还有其他方法可以在存储库中执行此操作吗?
【问题讨论】:
-
我认为在这种情况下我们可以使用 launch().. 不确定
-
希望做同样的事情。 @Cruces 有什么进展吗?
-
如果我没记错的话,我最终将范围传递给函数并在视图模型中运行了两个异步运行,现在方法是
fun showItem(scope:CoroutineScope, id:int),里面有两个val def1 = scope.async { .... }运行和回复在def1.await()和def2.awaitend 之后代码完成后发送,然后从 def2 检索结果并返回它
标签: android kotlin-coroutines coroutine