Book Image

Android Studio 4.0 Development Essentials - Kotlin Edition

By : Neil Smyth
Book Image

Android Studio 4.0 Development Essentials - Kotlin Edition

By: Neil Smyth

Overview of this book

Kotlin as an Android-compatible programming language is becoming increasingly popular. Fully updated for Android Studio 4.0, this book will teach you the skills necessary to develop Android-based applications using Kotlin. Starting with the basics, this book outlines the steps necessary to set up Android development and testing environments, and goes on to introduce you to programming in Kotlin. You’ll practice Java to Kotlin code conversion and explore data types, operators, expressions, loops, functions, as well as the basics of OOP in Kotlin. You’ll then learn about Android architecture components and advanced topics, such as intents, touchscreen handling, gesture recognition, multi-window support integration, and biometric authentication. As you make progress, you’ll explore Android Studio 4.0’s key features, including layout editor, direct reply notifications, and dynamic delivery. You’ll also delve into Android Jetpack and create a sample app project using ViewModel, the Android Jetpack component. Finally, you will upload your app to Google Play Console and model the build process using Gradle. By the end of this Android book, you’ll be fully prepared to develop applications using Android Studio 4.0 and Kotlin.
Table of Contents (97 chapters)
97
Index

65.9 Returning Results from a Coroutine

The above example ran a suspend function as a coroutine but did not demonstrate how to return results. Suppose, however, that the performSlowTask() function is required to return a string value which is to be displayed to the user via a TextView object.

To do this, we need to rewrite the suspend function to return a Deferred object. A Deferred object is essentially a commitment to provide a value at some point in the future. By calling the await() function on the Deferred object, the Kotlin runtime will deliver the value when it is returned by the coroutine. The code in our startTask() function might, therefore, be rewritten as follows:

fun startTask(view: View) {

    coroutineScope.launch(Dispatchers.Main) {

      statusText.text = performSlowTask().await()

    }

}

The problem now is that we are having to use the launch builder to start the coroutine...