Implementing the Activity
Creating MainActivity
It’s time to implement the code for the UI, starting with the landing page, which is the main activity. We’ll first write the code to handle the airport code that the user enters into the text box and the button click. Then we’ll write the code to populate the RecyclerView
with data obtained from the web service. That appears like a lot of work, but, surprisingly, we won’t need too much code to implement these actions. Let’s get started, one step at a time.
Coroutines in the UI
As the first step, let’s address head-on the need for coroutines in the UI. The UI will have to fetch the airport status from the web service, but we don’t want the UI to block and become inactive when the application is in the middle of network calls. To address this, we’ve already designed the getAirportStatus()
top-level function in AirportStatus
to be non-blocking, using the suspend
keyword. From Chapter 16, Exploring Coroutines, we know that functions marked with suspend
can’t be called from within arbitrary functions—they have to be called from within coroutines. There’s a catch, however—the UI code created by the Android Studio doesn’t use coroutines. So if we invoke getAirportStatus()
from an event handler, the code will fail compilation. In short, we have to run the UI code in a coroutine context so that the event handlers can call functions that are marked with suspend.
We can easily run the UI code as a coroutine by making a small change to the generated MainActivity
class—we’ll implement Kotlin’s CoroutineScope
and override the coroutineContext
property. With this change, the activity class can provide a coroutine scope for the execution of coroutines. Let’s make this change in the MainActivity.kt
file:
Get hands-on with 1400+ tech skills courses.