Programming Asynchronously
We'll cover the following...
sWhen programming modern applications we often have to make calls to remote services, update databases, perform searches, and the list goes on. Many of these tasks aren’t instantaneous. To improve program efficiency we may want to execute such operations asynchronously, in a non-blocking manner. Coroutines are intended to exactly solve that problem.
Starting sequentially
Let’s create a program to go out and get the weather details to see if there are any delays at certain airports. As a first step, we’ll create an Airport
class that will hold the data, along with a Weather
class to hold the temperature. We’ll use the Klaxon library to parse the JSON response from the Federal Aviation Administration (FAA) airport status web service.
import java.net.URLimport com.beust.klaxon.*class Weather(@Json(name = "Temp") val temperature: Array<String>)class Airport(@Json(name = "IATA") val code: String,@Json(name = "Name") val name: String,@Json(name = "Delay") val delay: Boolean,@Json(name = "Weather") val weather: Weather) {companion object {fun getAirportData(code: String): Airport? {val url = "https://soa.smext.faa.gov/asws/api/airport/status/$code"return Klaxon().parse<Airport>(URL(url).readText())}}}
In the Airport
class we use the @Json
annotation to map the properties in the JSON response to the properties in our class. In the getAirportData()
method we fetch the data, extract the text response, and parse the JSON content to create an instance of Airport
.
Given a list of airport codes, let’s first fetch the data sequentially using the method just described. This will soon help us compare the sequential, synchronous code for this program with the asynchronous version.
We’ll loop through the list of airports and fetch the airport status information, one at a time, and print the output in a perusable format. ...