我正在使用Kotlin协程从服务器获取数据,我将延迟传递给其他函数。如果服务器在2000毫秒内没有给出答案,我想从本地房间数据库(如果它存在于本地数据库中)中检索该对象,但如果我最终从服务器接收数据,我想保存在在本地数据库中以便将来调用。我该如何实现这一目标?我想过使用withTimeout,但在这种情况下,超时后没有等待服务器的响应。
override fun getDocument(): Deferred<Document> {
return GlobalScope.async {
withTimeoutOrNull(timeOut) {
serverC.getDocument().await()
} ?: dbC.getDocument().await()
}
}
我提出的一个想法:
fun getDocuments(): Deferred<Array<Document>> {
return GlobalScope.async {
val s = serverC.getDocuments()
delay(2000)
if (!s.isCompleted) {
GlobalScope.launch {
dbC.addDocuments(s.await())
}
val fromDb = dbC.getDocuments().await()
if (fromDb != null) {
fromDb
} else {
s.await()
}
} else {
s.await()
}
}
}
我建议使用select
库中的kotlinx.coroutines
表达式。
https://kotlinlang.org/docs/reference/coroutines/select-expression.html
fun CoroutineScope.getDocumentsRemote(): Deferred<List<Document>>
fun CoroutineScope.getDocumentsLocal(): Deferred<List<Document>>
@UseExperimental(ExperimentalCoroutinesApi::class)
fun CoroutineScope.getDocuments(): Deferred<List<Document>> = async {
supervisorScope {
val documents = getDocumentsRemote()
select<List<Document>> {
onTimeout(100) {
documents.cancel()
getDocumentsLocal().await()
}
documents.onAwait {
it
}
}
}
}
select表达式使用来自网络的onAwait
信号或超时恢复。在这种情况下,我们返回本地数据。
您可能也希望以块的形式加载文档,因为Channel
s可能也有帮助https://kotlinlang.org/docs/reference/coroutines/channels.html
最后,我们在示例中使用了kotlinx.coroutines的实验API,函数onTimeout
可能会在库的未来版本中发生变化