如何解决在Kotlin Coroutines中等待Java 5 Futures而不会阻塞线程
我有一个suspend
函数,我想从中返回Java 5 Future
的结果。未来对象来自另一个库Firebase Cloud Firestore- Admin SDK for Java,并提供了一个阻塞调用get()
来检索所述未来的结果。
我的功能看起来像这样-
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
}
我考虑过的解决方案
我考虑的第一件事是在kotlinx.coroutine
中寻找扩展桥梁的扩展。存在扩展名时,它们仅适用于CompletionStatge
。所以我决定将未来包装成一个()-
val snapshot = CompleteableFuture.supplyAsync {
db.collection("prefixes")
.document(messageCreateEvent.guildId.get().asString())
.get() // This returns a future
.get() // Get the result
}.await()
我经验不足,因此不确定这是否是正确的解决方案。我在一个编程社区中询问了我的问题,有人建议我使用Deferred
-
val deferred = CompletableDeferred<DocumentSnapshot>()
val future = db.collection("prefixes")
.document(messageCreateEvent.guildId.get().asString())
.get()
future.addListener(
Runnable { deferred.complete(future.get()) },ForkJoinPool.commonPool()
)
val snapshot = deferred.await()
我已经花了很多时间来寻找一种将期货与联套程序联系起来的方法,关于SO甚至没有类似的问题。通过,如果这个问题得到重复的标记,我不会感到惊讶。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。