Kotlin coroutines wait until

Kotlin Coroutines Wait Task to Complete

Assuming you launch a coroutines on main/ui thread to display result from an heavy io operation.

launch(Dispatchers.Main)  val result = runBlocking(Dispatchers.IO)  fetchSomething() > Toast.makeText(context, result, Toast.LENGTH_LONG).show()>
launch(Dispatchers.Main)  val queue = async(Dispatchers.IO)  fetchSomething() > val result = queue.await() Toast.makeText(context, result, Toast.LENGTH_LONG).show()>

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

Travelopy — discover travel places in Malaysia, Singapore, Taiwan, Japan.

Источник

Waiting for Coroutines in Kotlin

Join the DZone community and get the full member experience.

Coroutines allow you to execute tasks asynchronously without blocking the calling thread, such as the main thread. Great, but sometimes you will need to wait for all of these tasks to finish. In this post, we will look at how to wait for a coroutine to finish using join .

Note, async / await will not be covered here, as I will cover that in a later post. For now, read the Kotlin docs — Concurrent using async if that is what you are interested in.

How to Get a Job

No, you didn’t misread the heading, I will show you how to get a job:

 println("and it seems to work!")
 print("This is your first coroutine, ")

There, you now have a job. I have solved the world’s employment problems…

Ok, seriously, a Job is returned when you start a coroutine. In fact, from what I understand anyway, the words job and coroutine are interchangeable in this context. Really, they are the same thing, as seen below:

public abstract class AbstractCoroutinein T>(
 * The context of the parent coroutine.
 protected val parentContext: CoroutineContext,
) : JobSupport(active), Job, ContinuationT>, CoroutineScope

AbstractCoroutine implements the Job interface. So a coroutine is a job.

What to Do Once You Have a Job

You can control a coroutine through the functions available on the Job interface. Here are some of the functions (there are many more):

Further Job operations will be explored in future posts.

Waiting for a Coroutine

To wait for a coroutine to finish, you can call Job.join .

join is a suspending function, meaning that the coroutine calling it will be suspended until it is told to resume. At the point of suspension, the executing thread is released to any other available coroutines (that are sharing that thread or thread pool).

 val job: Job = launch(context = Dispatchers.Default) 
 println("[$] Launched coroutine")
 println("[$] Finished coroutine")
 println("[$] Created coroutine")
 println("[$] Finished coroutine")

In the snippet above, a coroutine is launched, and a Job is returned. join is then called on the created job/coroutine to wait for it to finish before resuming. This leads to the following output:

[DefaultDispatcher-worker-1] Launched coroutine
[DefaultDispatcher-worker-1] Finished coroutine

The main thread is blocked while it waits for the job/coroutine to finish. Note, that the main thread is used by runBlocking , while the child is launched using one of the default thread pools.

Just like futures and threads, many coroutines can be created and waited for through the use of join . This is also made slightly easier by the convenient joinAll extension function:

 launch(context = Dispatchers.Default) 
 println("[$] Launched coroutine: $it")
 println("[$] Finished coroutine: $it")
 println("[$] Created all coroutines")
 println("[$] Finished all coroutines")

Something similar to the following would be output:

[DefaultDispatcher-worker-1] Launched coroutine: 1
[DefaultDispatcher-worker-2] Launched coroutine: 2
[DefaultDispatcher-worker-3] Launched coroutine: 3
[DefaultDispatcher-worker-4] Launched coroutine: 4
[main] Created all coroutines
[DefaultDispatcher-worker-5] Launched coroutine: 5
[DefaultDispatcher-worker-1] Finished coroutine: 1
[DefaultDispatcher-worker-4] Finished coroutine: 4
[DefaultDispatcher-worker-2] Finished coroutine: 3
[DefaultDispatcher-worker-3] Finished coroutine: 5
[DefaultDispatcher-worker-5] Finished coroutine: 2
[main] Finished all coroutines

I wonder if you can guess what joinAll ’s implementation looks like. I don’t have any way to hide text, so I’ll just assume you actually guessed. I have added it below:

public suspend fun CollectionJob>.joinAll(): Unit = forEach < it.join() >

Joining Is Not Always Required

Joining all jobs running inside a coroutine is not a requirement to ensure their completion is waited for. By using the coroutineScope builder (a function), you can create a parent/child relationship between coroutines. More precisely, the coroutineScope builder will only progress once all of the coroutines inside it have completed. This is effectively doing a joinAll on all the jobs inside the coroutineScope .

The example below attempts to show this:

 val jobs: ListJob> = (1..2).map < parentNumber ->
 // This coroutine is joined on inside [runBlocking] to allow the last [println]
 launch(context = Dispatchers.Default) 
 // The [coroutineScope] block cannot be left until the 2 corountines launched inside have finished
 println("[$] Launched parent: $parentNumber")
 println("[$] Launched child: $parentNumber - $childNumber")
 println("[$] Finished child: $parentNumber - $childNumber")
 println("[$] Finished parent: $parentNumber")
 println("[$] Created all coroutines")
 println("[$] Finished all coroutines")

Which outputs something like this:

[DefaultDispatcher-worker-1] Launched parent: 1
[main] Created all coroutines
[DefaultDispatcher-worker-2] Launched parent: 2
[DefaultDispatcher-worker-3] Launched child: 2 - 1
[DefaultDispatcher-worker-4] Launched child: 1 - 1
[DefaultDispatcher-worker-5] Launched child: 1 - 2
[DefaultDispatcher-worker-3] Launched child: 2 - 2
[DefaultDispatcher-worker-2] Finished child: 2 - 1
[DefaultDispatcher-worker-3] Finished child: 2 - 2
[DefaultDispatcher-worker-5] Finished child: 1 - 2
[DefaultDispatcher-worker-1] Finished child: 1 - 1
[DefaultDispatcher-worker-2] Finished parent: 2
[DefaultDispatcher-worker-1] Finished parent: 1
[main] Finished all coroutines

Each parent coroutine had to wait until their children finished. This was enabled by using coroutineScope , ensuring each coroutine launched inside it had completed before moving on.

I only touched on this subject to show that joining is not the only way to wait for jobs to finish. For some more information, have a look at the Kotlin docs — Scope builder.

Summary

Sometimes you will want to wait for several coroutines to complete before moving on. This behavior can be achieved using join and joinAll provided by the Job interface. Doing so will suspend the calling coroutine until the joined jobs have concluded. Similar behavior can also be obtained via the coroutineScope builder, ensuring that all jobs launched within it have ended before continuing.

If you enjoyed this post or found it helpful (or both) then please feel free to follow me on Twitter at @LankyDanDev and remember to share with anyone else who might find this useful!

Published at DZone with permission of Dan Newton , DZone MVB . See the original article here.

Opinions expressed by DZone contributors are their own.

Источник

Читайте также:  Throw new error php
Оцените статью