Junaid Khan
Junaid Khan

Reputation: 315

How to run multiple kotlin couroutines in parallel android?

I am fetching images, videos and music files from android device. I want to run my code in background using three couroutines in parallel without blocking the UI thread.

suspend fun getImages() : ArrayList<VideoData> {
    
}
suspend fun getVideos() : ArrayList<ImageData> {

}
suspend fun getAudio() : ArrayList<AudioData> {

}

These three functions must execute in parallel. I do not want to wait for all of them to complete. When one function is completed I want to execute some code on main thread i.e UI thread.

Upvotes: 1

Views: 3019

Answers (1)

Saharsh
Saharsh

Reputation: 453

Using Coroutines is an option.

Create your suspend functions :

suspend fun getImages() : ArrayList<VideoData> {

    withContext(Dispatchers.IO) {
        // Dispatchers.IO
        /* perform blocking network IO here */
    }
}
suspend fun getVideos() : ArrayList<ImageData> {...}
suspend fun getAudio()  : ArrayList<AudioData> {...}

Create a Job

val coroutineJob_1 = Job()

Create a Scope

val coroutineScope_1 = CoroutineScope(coroutineJob + Dispatchers.Main)
       

Launch the Job with the scope, in your Activity/Fragment...

coroutineScope_1.launch {

     // Await
     val response = getImages()

     show(response)
}

show() has your UI code.

You can launch multiple Jobs to do work in parallel...

coroutineScope_2.launch {...}
coroutineScope_3.launch {...}

Upvotes: 2

Related Questions