Kotlin Coroutines : Waiting for multiple threads to finish

前端 未结 2 1920
旧巷少年郎
旧巷少年郎 2021-01-02 12:18

So looking at Coroutines for the first time, I want to process a load of data in parallel and wait for it to finish. I been looking around and seen RunBlocking and Await et

2条回答
  •  长情又很酷
    2021-01-02 12:51

    You don't need to manually keep track of your cuncurrent jobs if you use the concept of structured concurrency. Assuming that your processPages function performs some kind of blocking IO, you can encapsulate your code into the following suspending function, which executes your code in an IO dispatcher designed for this kind of work:

    suspend fun processAllPages() = withContext(Dispatchers.IO) { 
        // withContext waits for all children coroutines 
        launch { processPages(urls, collection) }
        launch { processPages(urls, collection2) }
        launch { processPages(urls, collection3) }
    }
    

    Now, from if a topmost function of your application is not already a suspending function, then you can use runBlocking to call processAllPages:

    runBlocking {
        processAllPages()
    }
    

提交回复
热议问题