[英]Accessing values outside a coroutine scope in Kotlin
I got this code right here, that works fine.我在这里得到了这段代码,效果很好。 I can print out the values i get from every job/coroutines that launches inside the scope.
我可以打印出从 scope 内启动的每个作业/协程中获得的值。 But the problem is that i struggle to use the values outside of the scope.
但问题是我很难使用 scope 之外的值。 The two jobs runs async and returns a list from a endpoint.
这两个作业异步运行并从端点返回一个列表。 How can i return result1 or result2?
如何返回 result1 或 result2? I have tried with global variables that is beeing assigned from the job, but it returns null or empty.
我尝试使用从作业中分配的全局变量,但它返回 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
}
If you want getSomethingAsync()
function to wait for getWhatever1()
and getWhatever2()
to finish, that means you need getSomethingAsync()
to not be asynchronous.如果您希望
getSomethingAsync()
function 等待getWhatever1()
和getWhatever2()
完成,这意味着您需要getSomethingAsync()
不是异步的。 Make it suspend
and remove ioScope.launch()
.使其
suspend
并删除ioScope.launch()
。
Also, if you want getWhatever1()
and getWhatever2()
to run asynchronously to each other and wait for their results, use async()
instead of launch()
:此外,如果您希望
getWhatever1()
和getWhatever2()
彼此异步运行并等待它们的结果,请使用async()
而不是launch()
:
suspend fun getSomething(): String = coroutineScope {
val job1 = async {
println("Network Request 1...")
getWhatever1() ////I want to use this value outside the scope
}
val job2 = async {
println("Network Request 2...")
getWhatever2() //I want to use this value outside the scope
}
val result1 = job1.await()
val result2 = job2.await()
//Return result1 and result2 //help
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.