小编Abh*_*oni的帖子

在 Kotlin 协程中等待 Java 5 Futures 而不阻塞线程

我有一个suspend函数,我想从中返回 Java 5 的结果Future。future 对象来自另一个库Firebase Cloud Firestore- Admin SDK for Java并提供阻塞调用get()来检索所述 future 的结果。

我的功能看起来像这样-

suspend fun getPrefix(messageCreateEvent: MessageCreateEvent): String {

    val snapshot = db.collection("prefixes")
        .document(messageCreateEvent.guildId.get().asString())
        .get() //This returns a future
        .get() //Retrieves the future's result (Blocks thread; IDE gives warning)

    //Return the prefix
    return if (snapshot.exists())
        snapshot.getString("prefix") ?: DEFAULT_PREFIX
    else DEFAULT_PREFIX
}
Run Code Online (Sandbox Code Playgroud)

我考虑过的解决方案

我考虑的第一件事是寻找kotlinx.coroutine扩展来连接未来。虽然存在扩展名,但它们仅适用于CompletionStatge. 所以我决定将未来包装成一个 ()-

val snapshot = CompleteableFuture.supplyAsync {
    db.collection("prefixes")
        .document(messageCreateEvent.guildId.get().asString())
        .get() // This returns a …
Run Code Online (Sandbox Code Playgroud)

java concurrency kotlin google-cloud-firestore kotlin-coroutines

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