Accessing values outside a coroutine scope in Kotlin

1.7k Views Asked by At

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 
}
1

There are 1 best solutions below

1
On

If you want getSomethingAsync() function to wait for getWhatever1() and getWhatever2() to finish, that means you need getSomethingAsync() to not be asynchronous. Make it suspend and remove 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():

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
}