【问题标题】:Accessing values outside a coroutine scope in Kotlin在 Kotlin 中访问协程范围之外的值
【发布时间】: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


    【解决方案1】:

    如果您希望getSomethingAsync() 函数等待getWhatever1()getWhatever2() 完成,这意味着您需要getSomethingAsync() 不是异步的。设为suspend 并删除ioScope.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
    }
    

    【讨论】:

    • 谢谢你!必须添加异步(Dispatchers.IO)才能运行异步作业。
    猜你喜欢
    • 2019-06-22
    • 2017-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-18
    • 2010-09-25
    • 1970-01-01
    相关资源
    最近更新 更多