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
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With