【发布时间】:2022-01-23 21:45:46
【问题描述】:
我在这里得到了这个代码,它工作得很好。我可以打印出我从范围内启动的每个作业/协程中获得的值。但问题是我很难使用范围之外的值。这两个作业异步运行并从端点返回一个列表。如何返回 result1 或 result2?我尝试使用从作业中分配的全局变量,但它返回 null 或空。
private val ioScope = CoroutineScope(Dispatchers.IO + Job())
fun getSomethingAsync(): String {
ioScope.launch {
val job = ArrayList<Job>()
job.add(launch {
println("Network Request 1...")
val result1 = getWhatever1() ////I want to use this value outside the scope
})
job.add(launch {
println("Network Request 2...")
val result2 = getWhatever2() //I want to use this value outside the scope
})
job.joinAll()
}
//Return result1 and result2 //help
}
【问题讨论】:
标签: java kotlin kotlin-coroutines kotlinx.coroutines.flow