Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/logging/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Kotlin协程中等待Java5未来,而不阻塞线程_Java_Kotlin_Google Cloud Firestore_Concurrency_Kotlin Coroutines - Fatal编程技术网

在Kotlin协程中等待Java5未来,而不阻塞线程

在Kotlin协程中等待Java5未来,而不阻塞线程,java,kotlin,google-cloud-firestore,concurrency,kotlin-coroutines,Java,Kotlin,Google Cloud Firestore,Concurrency,Kotlin Coroutines,我有一个suspend函数,我想从中返回Java 5Future的结果。future对象来自另一个库,并提供一个阻塞调用get(),以检索所述future的结果 我的函数如下所示- suspend fun getPrefix(messageCreateEvent:messageCreateEvent):字符串{ val snapshot=db.collection(“前缀”) .document(messageCreateEvent.guildId.get().asString()) .get(

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

我的函数如下所示-

suspend fun getPrefix(messageCreateEvent:messageCreateEvent):字符串{
val snapshot=db.collection(“前缀”)
.document(messageCreateEvent.guildId.get().asString())
.get()//这将返回一个未来
.get()//检索未来的结果(阻止线程;IDE发出警告)
//返回前缀
返回if(snapshot.exists())
snapshot.getString(“前缀”)?:默认前缀
else默认前缀
}
我考虑过的解决办法 我考虑的第一件事是在
kotlinx.coroutine
中寻找连接未来的扩展。虽然存在扩展,但它们仅适用于
CompletionStatge
。所以我决定把未来包装成一个()-

val snapshot=completablefuture.supplyAsync{
db.collection(“前缀”)
.document(messageCreateEvent.guildId.get().asString())
.get()//这将返回一个未来
.get()//获取结果
}.等待
我非常缺乏经验,也不确定这是否是正确的解决方案。我在一个编程社区询问了我的问题,在那里有人建议我使用一个
Deferred
-

val deferred=CompletableDeferred()
val future=db.collection(“前缀”)
.document(messageCreateEvent.guildId.get().asString())
.get()
future.addListener(
Runnable{deferred.complete(future.get())},
ForkJoinPool.commonPool()
)
val snapshot=deferred.await()

我花了相当长的时间来寻找一种将期货与共同惯例联系起来的方法,甚至没有类似的问题。尽管如此,如果这个问题有重复标记,我也不会感到惊讶。

怎么样?@minizibi感谢您的评论。是的,我已经检查了它们(甚至在我的问题中提到过),没有扩展来等待
未来的
对象。