Kotlin Coroutines - How to block to await/join all jobs?

后端 未结 3 1163
滥情空心
滥情空心 2021-01-18 07:17

I am new to Kotlin/Coroutines, so hopefully I am just missing something/don\'t fully understand how to structure my code for the problem I am trying to solve.

Essen

3条回答
  •  梦毁少年i
    2021-01-18 07:47

    mutableListOf() creates an ArrayList, which is not thread-safe.
    Try using ConcurrentLinkedQueue instead.

    Also, do you use the stable version of Kotlin/Kotlinx.coroutine (not the old experimental one)? In the stable version, with the introduction of structured concurrency, there is no need to write jobs.joinAll anymore. launch is an extesion function of runBlocking which will launch new coroutines in the scope of the runBlocking and the runBlocking scope will automatically wait for all the launched jobs to finsish. So the code above can be shorten to

    val lstOfReturnData = ConcurrentLinkedQueue()
    runBlocking {
            lstInputs.forEach {
                launch(Dispatches.IO) {
                    lstOfReturnData.add(networkCallToGetData(it))
                }
            }
    }
    return lstOfReturnData
    

提交回复
热议问题