Parallel Job in Coroutine using Kotlin…

Saqib Ahmed
3 min readFeb 25, 2022

You wanna know about how to use and work with the parallel job in coroutine using kotlin. Let’s get started…

A coroutine is a concurrency design pattern that you can use on Android to simplify code that executes asynchronously. To use multi-thread in the android, one must use the Handler(), Looper() to handle multiple threading which is more complex and sometimes thread blocking environment.

Focus, On the coroutine part, the coroutine doet not block the main thread, it suspend the main theread. which means that the ui component can be update while making a network call.

Coroutine use Main-Safety:

A coroutine use dispatchers to determine which threads are used for coroutine execution. In Kotlin, all coroutines must run in a dispatcher, even when they’re running on the main thread.Basically there are three type of coroutine dispatchers.

  1. Dispatchers.Main : It is running on the main android thread.
  2. Dispatchers.IO : It is running outside of the main Theard.mostly used for the disk or network I/O operation. The main thread is not effected.
  3. Dispatchers.Default : It is optimized to perform CPU-intensive work outside of the main thread.

Jobs:

A job is a handle to a coroutine. a job can be created using the two function launch and async . Each coroutine that you create return a job instance. So, a job can work with lifecycle of the coroutine, means that a job can be control inside the coroutine, a job can be cancelled or can join to another job. A coroutine can have number of job in it. A job is independent of each other, but can be controlled using coroutine. That’s give the ability to run as parallel.

To know more about the Job in coroutine check out here.

Use in Code:

Firstly, implement the dependencies of the coroutine’s in the app build.gradle file.

dependencies {
def coroutines_version = "1.3.9"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:$coroutines_version"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutines_version"
}

You can use latest coroutine version by the time you use. I’m gonna leave it up to you.

class MainActivity : AppCompatActivity() {override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
CoroutineScope(Dispacthers.IO).launch {
// This is a coroutine Block.
}
}
}

A job can be created using the launch which give the instance of the job return.

Now we are calling network call from inside the coroutine job. the function need to mark as suspended.For simply understanding, i am hitting a sample API. we need to create the another job inside our coroutine scope.

For see how the parallel job work , we simply add measure the time the API hit the call and return data. To measure the time taken by the API , add the following code below in your activity.

In the above code, we have created the two job inside the coroutine scope and to measure the time we calculate the job1 and job2 time taken minus the total time taken by the coroutineScope.

Now the setTextOnMainThread contains the result , but there is something called withContext() and what it does is it shift the our Dispatchers to main android thread. Remember, we call the coroutine scop in IO. dispacthers which basically transferred the control to IO which free our main thread, to write or make contack with UI, we need the main thread. So the withContext() shift the control back to main thread.so, we can put the result in UI/Screen.

private fun setNewText(input: String) {
val newText = text_view.text.toString() + "\n$input"
text_view.text = newText
}

private suspend fun setTextOnMainThread(input: String) {
withContext(Dispatchers.Main) {
setNewText(input)
}

}

We can see the result in our Log catalog.

The Job1 is delay for the (2000 ms) and job2 is delay for the (1000 ms). As we can see from our catalog that the total time taken is only (2000 ms) . which means that the Longest job is the total time taken . Both API runs parellel and doesn’t effect each other.

The Beauty of the Coroutine.

Output:

Check out the complete code in my repo.Click Here

Happy Learning , Happy Coding… Thank you.

--

--

Saqib Ahmed

I'm basically a mobile developer and became a self-time freelance writer. I spend most of my time with tech related stuff. I’m sharing my learning with you!