小编tom*_*mmy的帖子

Kotlin 协程 - 如果一段时间后第一个任务没有完成,则开始另一个任务

我正在使用 Kotlin 协程从服务器获取数据,并将延迟传递给其他函数。如果服务器在 2000 毫秒内没有给出答案,我想从本地 Room DB 检索对象(如果它存在于本地数据库中),但如果我最终从服务器收到数据,我想保存在在本地数据库中以供将来调用。我怎样才能做到这一点?我想过使用withTimeout,但是在这种情况下,超时后没有等待服务器的响应。

override fun getDocument(): Deferred<Document> {
    return GlobalScope.async {
        withTimeoutOrNull(timeOut) {
            serverC.getDocument().await()
        } ?: dbC.getDocument().await()
    }
}
Run Code Online (Sandbox Code Playgroud)

我想到的一个想法:

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()
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

database android coroutine kotlin kotlin-coroutines

5
推荐指数
1
解决办法
1455
查看次数

标签 统计

android ×1

coroutine ×1

database ×1

kotlin ×1

kotlin-coroutines ×1