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
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.
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.
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.