简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM