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. But the problem is that i struggle to use the values outside of the scope. The two jobs runs async and returns a list from a endpoint. How can i return result1 or result2? I have tried with global variables that is beeing assigned from the job, but it returns null or empty.
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 forgetWhatever1()
andgetWhatever2()
to finish, that means you needgetSomethingAsync()
to not be asynchronous. Make itsuspend
and removeioScope.launch()
.Also, if you want
getWhatever1()
andgetWhatever2()
to run asynchronously to each other and wait for their results, useasync()
instead oflaunch()
: