Making HTTP requests with Coroutines in Android

Coroutines are a powerful feature in Kotlin to write asynchronous code that can look like synchronous code. Volley is a popular Android library for making HTTP requests. By combining the two we can drastically simplify code that depends on multiple API calls

Making HTTP requests with Coroutines in Android
Photo by Jannes Glas / Unsplash

Coroutines are a powerful feature in Kotlin to write asynchronous code that can look like synchronous code. Volley is a popular Android library for making HTTP requests. By combining the two we can drastically simplify code that depends on multiple API calls (as shown in the example below).

First is the suspend function (coroutine). Here we make use of suspendCoroutine  because it gives us the cont (continuation) parameter we need in order to resume the executor.

suspend fun get(url: String, requestQueue: RequestQueue) = suspendCoroutine<Either<String, VolleyError>> { cont ->
        println("get: $url")
        requestQueue.add(StringRequest(
            Request.Method.GET, url,
            { response -> cont.resume(Either.Left(response)) },
            { error -> cont.resume(Either.Right(error)) }
        ))
    }
coroutine

Pretty simple right? In your success and error handlers you just call the continuation with the result value/s. In this case I am using the Either type provided by the Arrow library.

The missing piece of the puzzle is that you cannot just call a coroutine (suspend function) from a regular function. This is because it needs to run within a Executor/Dispatch/Job scope for all the wiring as waking to be handled for you. Below is how I create the scope object by latching on to the Main Dispatcher.

val scope = CoroutineScope(Job() + Dispatchers.Main)
scope.launch {
    val resultA = get("https://www.example.com")
    val resultB = get("https://www.example.com")
    val resultC = get("https://www.example.com")
    // Do something with all of your results
}
caller

In this case I use launch which pushes off to the executor in a fire and forget manner. async is another option if you need to return a value.

More Information