Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to launch 10 coroutines in for loop and wait until all of them finish?

I need to fill list of objects from DB. And before passing value to itemes I want all of them to finish. Is here any short way calling await() for each item to wait. I want to make clean code, May be some design pattern or trick?

    for (x in 0..10) {
        launch {
            withContext(Dispatchers.IO){
                list.add(repository.getLastGame(x) ?: MutableLiveData<Task>(Task(cabinId = x)))
            }

        }

    }
    items.value = list
like image 489
Nurseyit Tursunkulov Avatar asked Apr 27 '19 05:04

Nurseyit Tursunkulov


People also ask

What is the difference between async and launch when executing coroutines?

The main difference between async and launch is that launch is used for starting a computation that isn't expected to return a specific result. launch returns Job , which represents the coroutine. It is possible to wait until it completes by calling Job.

What is run blocking in coroutines?

runBlocking starts the coroutine which calls CoroutineScheduler. dispatch(). dispatch() posts targeted runnable block of code to main thread handler. BlockingCoroutine blocks current thread with LockSupport.

How do I launch coroutines?

launch. The simplest way to create a coroutine is by calling the launch builder on a specified scope. It Launches a new coroutine without blocking the current thread and returns a reference to the coroutine as a Job. The coroutine is canceled when the resulting job is canceled.

How do you wait for coroutine to finish?

We can wait for the coroutine to finish by calling join() on the Job. For example, suppose we have a suspend function to download some files. We can launch this coroutine and capture the resulting job, which we can later use to join — to wait for the operation to complete.


1 Answers

coroutineScope { // limits the scope of concurrency
    (0..10).map { // is a shorter way to write IntRange(0, 10)
        async(Dispatchers.IO) { // async means "concurrently", context goes here
            list.add(repository.getLastGame(x) ?: MutableLiveData<Task>(Task(cabinId = x)))
        }
    }.awaitAll() // waits all of them
} // if any task crashes -- this scope ends with exception
like image 133
Roman Elizarov Avatar answered Oct 17 '22 06:10

Roman Elizarov