Skip to main content

Kotlin Coroutines, the non-confusing one 

Kotlin Coroutines, the non-confusing one .
Being inspired from my first lame post about coroutines, this time I decided to get real focus on the coroutines, rather than the setup of…

Being inspired from my first lame post about coroutines, this time I decided to get real focus on the coroutines, rather than the setup of Dagger or the ViewModel before the work.


Coroutines are lightweight threads. What this means is that coroutines do not create a real new thread in your processor. These threads are just simple objects which imitate the way of how threads work. Coroutines are created to make asynchronous programming simple.

Note: This posts use cases are in the Android framework.


Add the dependency to your build.gradle module app file :

implementation ‘org.jetbrains.kotlinx:kotlinx-coroutines-core:1.2.1’

Need to know:

To start a coroutine, you need a CoroutineContext.For that, you will need a Job and a CoroutineScope. A Job is nothing more than a way, so you can keep track of what coroutine is doing. Also the job makes working simple because it handles the coroutines according to the Activity/Fragment lifecycle (or the ViewModel).You can cancel this job when Activity/Fragment has finished.The CoroutineScope is a combination between the Job()and the Dispatchers.*, which is telling the framework what thread the job is going to be executed. If you do not declare a Job() the CoroutineScope will provide it for you. However, you cannot keep track of that job depending on the lifecycle .

The use case:

I need to get some data from the server via Json, the server will give me some values which I will save to the SharedPreferences. After that I am going to update the UI with those saved values.


Best practice is to use coroutines inside the ViewModel. But if you don’t what to use it, initialise in the Activity/Fragment class.

The CoroutineScope is being used in the IO thread. The IO thread is any thread but the Main thread. I could have started the CoroutineScope on the Main thread, but this is not my use case. My primary work is on the network than in the UI, thus there is pretty logical to me to start the coroutine on the IO thread. The plus operator there just defines the threading policy between the scope and the job. Together they make the CoroutineScope. The Dispatchers class has 4 types.

  • Default: The Default type is used when no CoroutineContext has been specified.
  • Main: Refers to the main thread, where the UI lies.
  • Unconfirmed: A coroutine dispatcher that is not confined to any specific thread.
  • IO: Designed for offloading blocking IO tasks to share pool of threads.
Note: You must finish the job when the Activity/Fragment/ViewModel has finished. In my case:


First of all I will need to specify the network call using retrofit:

Nothing new here apart from the Deferred type. The Deferred type is nothing but a class telling the software that what it provides is going to be delayed. Logic says: don’t run this on the main thread .

Note: I am not providing the retrofit setup.
Also note: As for the Deferred approach on Retrofit, it won’t be too long in this way. Please refer this link if you want to know more.

A method inside a coroutine, except from the methods that run on the main thread, must be marked with the suspend keyword, or on this case should return a Deferred type, if they return something that delays.


The loadPrayerTimes() is the method where the coroutine starts. If a condition is met, I start making the api call, else I need to tell user something (on the main thread).The withContext is basically the way to change the CoroutineContex. Now let’s jump to the makePrayersApiCall() method. It is marked with a suspend keyword as mentioned before. Everything that runs inside this method, is running on the IO thread. Why? Because that is the scope where I started in the initialisation. Basically, I update the UI on the beginning (where I load some progress bar) and in the end (where I show the data or I show error). One last thing we have not yet mentioned is the .await() method, which basically makes my request wait, until it gets the response but not by blocking the UI . The execution continues asynchronously.

More to know:

If you want to use kotlin coroutines only in the ViewModel, Google provides some implementation described here.


Using the kotlin coroutines is fun, simple and short. I personally found hard time using RxJava (which is awesome, but hard) and also Java’s AsyncTask. 
Coroutines made me understand the asynchronous programming more than I could imagine, and now they are helping me build a full project using them.


KotlinConf 2018 — Kotlin Coroutines in Practice by Roman Elizarov

Droidcon NYC 2018 — Coroutines by Example

Popular posts from this blog

What I learned from Kotlin Flow API

I used to check the docs and just read a lot about flows but didn't implement anything until yesterday. However, the API tasted really cool (even though some operations are still in Experimental state).Prerequisites: If you don't know RxJava it's fine. But a RxJava recognizer would read this faster.Cold vs Hot streamsWell, I really struggled with this concept because it is a little bit tricky. The main difference between cold and hot happened to be pretty simple: Hot streams produce when you don't care while in cold streams, if you don't collect() (or RxJava-s equivalent subscribe()) the stream won't be activated at all. So, Flows are what we call cold streams. Removing the subscriber will not produce data at all, making the Flows one of the most sophisticated asynchronous stream API ever (in the JVM world). I tried to make a illustration of hot and cold streams: Since I mentioned the word asynchronous this implies that they do support coroutines also. Flows vs…

Modularizing your Android app, breaking the monolith (Part 1)

Inspired by a Martin Fowlers post about Micro Frontends, I decided to break my monolithic app into a modular app. I tried to read a little more about breaking monolithic apps in Android, and as far as I got, I felt confident to share my experience with you. This will be some series of blog posts where we actually try to break a simple app into a modularized Android app.

Note: You should know that I am no expert in this, so if there are false statements or mistakes please feel free to criticize, for the sake of a better development. 

What do you benefit from this approach:
Well, people are moving pretty fast nowadays and delivery is required faster and faster. So, in order to achieve this, modularising Android apps is really necessary.You can share features across different apps. Independent teams and less problems per each.Conditional features update.Quicker debugging and fixing.A feature delay doesn't delay the whole app. As per writing tests, there is not too much difference about…

From Gson to Moshi, what I learned

There is no doubt that people are getting away from GSON and I agree with those reasons too. The only advantage GSON has over other parsing libraries is that it takes a really short amount of time to set up. Furthermore, the most important thing is that Moshi is embracing Kotlin support.

First let's implement the dependency:
implementation("com.squareup.moshi:moshi:1.8.0") It's not a struggle to migrate to Moshi. It's really Gson look-a-like. The only thing to do is annotate the object with @field:Json instead of @SerializedName (which is Gsons way for JS representation):

data class User( //GSON way @SerializedName("name") val name: String, @SerializedName("user_name") val userName: String, @SerializedName("last_name") val lastName: String, @SerializedName("email") val email: String ) data class User( //Moshi way @field:Json(name = "name") val name: String, @field:Json(name = "user_name…