Sitemap
Ronak Sethi

Ronak Sethi

SD2 (Android) | JAVA | Kotlin

Exploring Coroutine — Android

4 min readMay 11, 2020

--

A coroutine is a concurrency design pattern that you can use on Android to simplify code that executes asynchronously. Coroutines were added to Kotlin in version 1.3 and are based on established concepts from other languages.

On Android, coroutines help to solve two primary problems:

  • Manage long-running tasks that might otherwise block the main thread and cause your app to freeze.
  • Providing main-safety, or safely calling network or disk operations from the main thread.

The most interesting thing is that a thread can stop executing a coroutine at some specific “suspension points”, and go do some other work. It can resume executing the coroutine later on, or another thread could even take over.

When we use GlobalScope.launch, we create a top-level coroutine. Even though it is light-weight, it still consumes some memory resources while it runs. If we forget to keep a reference to the newly launched coroutine it still runs.

Suspending functions

You may find functions like kotlinx’s delay or Ktor’s HttpClient.post that need to wait for something or do intensive work before returning, and are marked with the suspend keyword.

suspend fun delay(timeMillis: Long) {...}
suspend fun someNetworkCallReturningValue(): SomeType {
...
}

These are called suspending functions. As we’ve just seen:

Suspending functions may suspend the execution of the current coroutine without blocking the current thread.

Using coroutines for long-running tasks

Coroutines are a way to simplify the code used to manage long-running tasks like fetchDocs. To explore how coroutines make the code for long-running tasks simpler, let’s rewrite the callback example above to use coroutines.

// Dispatchers.Main
suspend fun fetchData() {
// Dispatchers.Main
val result = get(url-here)
// Dispatchers.Main
show(result)
}
suspend fun get(url: String) = withContext(Dispatchers.IO){/*...*/}
//Dispatcher.IO -main safety block

Doesn’t this code block the main thread? How does it return a result from get without waiting for the network request and blocking? It turns out coroutines provide a way for Kotlin to execute this code and never block the main thread.

Get Ronak Sethi’s stories in your inbox

Join Medium for free to get updates from this writer.

Coroutines build upon regular functions by adding two new operations. In addition to invoke (or call) and return, coroutines add suspend and resume.

  • suspend — pause the execution of the current coroutine, saving all local variables
  • resume — continue a suspended coroutine from the place it was paused
Press enter or click to view image in full size

This functionality is added by Kotlin by the suspend keyword on the function. You can only call suspend functions from other suspend functions, or by using a coroutine builder like launch to start a new coroutine.

Suspend and resume work together to replace callbacks.

Dispatchers

  1. Dispatchers.Main
    Main thread on Android, interact with the UI, and perform light work.
    — Calling suspend functions
    — Call UI functions
    — Updating LiveData
  2. Dispatchers.IO
    Optimized for disk and network IO off the main thread.
    — Database*
    — Reading/writing files
    — Networking**
  3. Dispatchers.Default
    Optimized for CPU intensive work off the main thread.
    — Sorting a list
    — Parsing JSON
    — DiffUtils

Coroutine with Retrofit

Coroutines give us all the benefit of asynchronous and non-blocking behavior but without the lack of readability. We’ll see how we can use coroutines to perform network requests without blocking the underlying thread and without using callbacks. For network requests, we’ll use the Retrofit library which already supports coroutines.

Here, I have done an example to fetch a list of news sources:

Firstly add the dependency for coroutine:

implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.72"

Source Item class

class Source {
var key: String? = null
var name: String? = null
var lang: String? = null
var img: String? = null
}

Interface for network request

interface MyApi {
@GET("/news_source")
suspend fun getAllSources(
@Query("api_key") api_key: String?
): Response<List<SourceBean>>
}

Here we create retrofit to use it with coroutine in the GlobalScope to fetch data.

val retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(MyApi::class.java)

GlobalScope.launch(Dispatchers.Main) {
val comments = withContext(Dispatchers.IO) { retrofit.getAllSources(API_KEY) }
comments.body()?.let { setUpRecyclerView(it) }
}

Now u can see in the last code that I used a function of setUpRecyclerView() which basically is to display the data fetched to the screen using recycler view.

That’s it from my side.
Thank you for reading!

To know more about coroutine just go through these links:

Clap for it, if you like it!

--

--

Ronak Sethi
Ronak Sethi

Written by Ronak Sethi

SD2 (Android) | JAVA | Kotlin