Taking the App for a Drive

Let’s write a main() function to call the getAirportStatus() function with a few different airport codes and print the status of the airports with those codes to the console. Create a file named AirportApp.kt in the directory src/main/kotlin/com/agiledeveloper/ui and key in the following code:

 package​ ​com.agiledeveloper.ui
 
 import​ ​kotlinx.coroutines.*
 import​ ​com.agiledeveloper.airportstatus.*
 
 fun​ ​main​() = runBlocking {
  getAirportStatus(listOf(​"SFO"​, ​"IAD"​, ​"IAH"​, ​"ORD"​, ​"LAX"​))
  .forEach { println(it) }
 }

Since getAirportStatus() is a function that may be suspended, it can only be called within a coroutine. So we invoke it from within the block passed to the runBlocking() function. Whatever data is returned for each airport is printed in the lambda provided to the forEach() function. Since the data obtained by this program is real, the output will be different for each run.

The Gradle build file uses the application plugin to specify the main class. The Maven build file creates the manifest information with the main class. We can easily run the program:

If using Gradle, run this command:

 $ ​​gradlew​​ ​​run

If using Maven, run the following command:

 $ ​​java​​ ​​-jar​​ ​​target/airportapp-1.0-jar-with-dependencies.jar

Here’s one sample output from the program execution:

 Airport(code=ORD, name=Chicago O'hare Intl, delay=true)
 Airport(code=IAH, name=George Bush Intercontinental/houston, delay=true)
 Airport(code=LAX, name=Los Angeles Intl, delay=false)
 Airport(code=SFO, name=San Francisco Intl, delay=true)
 Airport(code=IAD, name=Washington Dulles Intl, delay=false)

Try including other airports, along with invalid airports or airports not supported by the web service, to see how the program behaves. Also, see if the program fails gracefully if there’s no network connection.

You can find the final code, including the tests and the build files in the unittest/final/airportapp directory.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.107.241