Better Programming

Advice for programmers.

Follow publication

Member-only story

Kotlin Coroutines, From the Basic to the Advanced

Siva Ganesh Kantamani
Better Programming
Published in
9 min readJan 15, 2020
Image source: Siva Ganesh Kantamani

1. Why Do We Need Coroutines?

Let’s say you have to get a bunch of customers from a list from your server. You have to make a service call to fetch the data and show them in a RecyclerView.

Let’s say you have a function fetchCustomers() in which you fetch data from the server, as shown below.

fun fetchCustomers(){
val array = api.fetchCustomersList()
updateUI(array)
}

If you do this, your app will crash as you’re operating on the main thread. You might find an alternative to invoke it by wrapping inside a thread. The next problem will be the lifecycle management. So you’ll switch to callbacks with subscription and cancellation to solve the problem. Soon you’re going to end up as shown below.

fun onDestroy(){
subscription1.cancel()
subscription2.cancel()
subscription3.cancel()
subscription4.cancel()
}

Coroutines will help you to escape from this callback hell. You might solve this problem using disposables in RxJava, but this might complicate the things. RxJava is as much of a headache as it is useful.

So what’s the solution? Here come coroutines, simple yet comprehensive.

2. Basics of Coroutines

Coroutines are nothing but lightweight threads on which we can execute tasks either related to background or UI changes, based on the context you choose.

Let’s write above fetchCustomers() using a Kotlin coroutine.

suspend fun fetchCustomers(){
val array = api.fetchCustomersList()
updateUI(array)
}

To show that this function runs on the coroutine, we use a suspend modifier. It works similarly to callback style but uses less code with no subscriptions. It’s easy to implement and easy to use just like that. You don’t need to learn anything new in the style of execution. Coroutines provide async execution in a sequential manner.

What it does is that when you start to execute a coroutine, it suspends the execution, and when it gets the response, it resumes the execution from where it’s been suspended. This…

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Responses (3)

Write a response