Updated 28 February 2022
In this blog, we are going to learn about how we can handle multiple coroutines in Kotlin.
When we launch coroutines in Kotlin using launch it returns a Job object as a result
We can manage that coroutine with the help of the Job object. Like it can be used to wait for the coroutine to do some work or it can be used to cancel the coroutine.
Coroutines can be controlled through the functions that are available on the Job interface. Some functions out of many that job interface offers are as follows:
join() function is a suspending function, It can be called from a coroutine or from within another suspending function. Job blocks all the threads until the coroutine finished its work.
cancel() method is used to cancel the coroutine, without waiting for it to finish its work. It can be said that it is just opposite to that of the join method.
Here we have created a fakeDownload function :
1 2 3 |
suspend fun fakeDownload(){ // Downloading ... } |
We launch a coroutine to get the job as a result. Which we can later use to join to wait for the operation to complete.
1 2 3 4 5 |
val job = launch { fakeDownload() } job.join() // This line will not run untill the downloading gets finised. |
We can also use multiple joins for multiple coroutines to perform their task and wait for completion. For example :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
val downloadImage = launch { fakeDownload() } val downloadFile = launch { fakeDownload() } val downloadAudio = launch { fakeDownload() } val downloadVideo= launch { fakeDownload() } downloadImage.join() downloadFile.join() downloadAudio.join() downloadVideo.join() // This line of execution will wait for finishing the downloading. |
Let’s clean up a little bit by using Collection<Job>.joinAll().
For example :
1 2 3 4 5 6 7 8 |
val downloadList = listOf( launch { fakeDownload() }, launch { fakeDownload() }, launch { fakeDownload() }, ) downloadList.joinAll() // This line will not run until all the downloading gets finished. |
To learn more about Kotlin & Coroutines, you can also refer to this link -> Coroutines Guide
That’s done. I hope, this blog will be helpful to you.
Reference: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/index.html
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.