1

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.

Junaid Khan
  • 315
  • 5
  • 16
  • Isn't https://stackoverflow.com/questions/57457079/run-two-kotlin-coroutines-inside-coroutine-in-parallel basically the same? – Cobalt Nov 11 '20 at 09:37

1 Answers1

1

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 {...}
Saharsh
  • 383
  • 2
  • 11
  • https://medium.com/androiddevelopers/coroutines-on-android-part-i-getting-the-background-3e0e54d20bb Have a look at this for more details on using Coroutines... – Saharsh Nov 11 '20 at 10:35
  • 1
    I want to execute them in parallel. launch vs async? where is the use of async? – Junaid Khan Nov 11 '20 at 10:39
  • You can launch multiple Jobs to do work in parallel... coroutineScope_2.launch {...} coroutineScope_3.launch {...} – Saharsh Nov 11 '20 at 10:40
  • https://stackoverflow.com/a/46226519/6269691 Have a look at this for the difference between launch vs async, Basically in launch, you will do all the work inside and not wait for any results as such. For async you get the result and then do it at the place you called it... – Saharsh Nov 11 '20 at 10:41