Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Mastering Kotlin for Android 14

You're reading from  Mastering Kotlin for Android 14

Product type Book
Published in Apr 2024
Publisher Packt
ISBN-13 9781837631711
Pages 370 pages
Edition 1st Edition
Languages
Author (1):
Harun Wangereka Harun Wangereka
Profile icon Harun Wangereka

Table of Contents (22) Chapters

Preface 1. Part 1: Building Your App
2. Chapter 1: Get Started with Kotlin Android Development 3. Chapter 2: Creating Your First Android App 4. Chapter 3: Jetpack Compose Layout Basics 5. Chapter 4: Design with Material Design 3 6. Part 2: Using Advanced Features
7. Chapter 5: Architect Your App 8. Chapter 6: Network Calls with Kotlin Coroutines 9. Chapter 7: Navigating within Your App 10. Chapter 8: Persisting Data Locally and Doing Background Work 11. Chapter 9: Runtime Permissions 12. Part 3: Code Analysis and Tests
13. Chapter 10: Debugging Your App 14. Chapter 11: Enhancing Code Quality 15. Chapter 12: Testing Your App 16. Part 4: Publishing Your App
17. Chapter 13: Publishing Your App 18. Chapter 14: Continuous Integration and Continuous Deployment 19. Chapter 15: Improving Your App 20. Index 21. Other Books You May Enjoy

Network Calls with Kotlin Coroutines

Most of the apps we use on our phones fetch data that is hosted online on a server. As such, we developers have to understand how to request and send data to the servers too. In this chapter, we will learn how to send and request data that is hosted online and display it in our apps.

In this chapter, we will learn how to perform network calls with a networking library, Retrofit. We will learn how to consume application programming interfaces (APIs) using this library. Moreso, we will learn how to take advantage of Kotlin coroutines to perform asynchronous network requests in our app.

In this chapter, we’re going to cover the following main topics:

  • Setting up Retrofit
  • Introduction to Kotlin coroutines
  • Using Kotlin coroutines for network calls

Technical requirements

To follow the instructions in this chapter, you will need to have Android Studio Hedgehog or later (https://developer.android.com/studio) downloaded.

You can find the code for this chapter at https://github.com/PacktPublishing/Mastering-Kotlin-for-Android/tree/main/chaptersix.

Setting up Retrofit

Retrofit is a type-safe REST client for Android, Java, and Kotlin developed by Square. The library provides a powerful framework for authenticating and interacting with APIs and sending network requests with OkHttp. In this book, we will be using Retrofit to perform our network requests.

To begin with, we will add the Retrofit dependencies using our newly created version catalog. Let’s define the versions in the libs.versions.toml file as follows:

retrofit = "2.9.0"
retrofitSerializationConverter = "1.0.0"
serializationJson = "1.5.1"
coroutines = "1.7.3"
okhttp3 = "4.11.0"

Next, let’s define the libraries in the libs.versions.toml file in the libraries section of our versions catalog as follows:

retrofit = { module = "com.squareup.retrofit2:retrofit" , version.ref = "retrofit" }
retrofit-serialization = { module = "com.jakewharton.retrofit:retrofit2-kotlinx-serialization...

Introduction to Kotlin coroutines

Coroutines, introduced by JetBrains for Kotlin, provide a way to write asynchronous code in a more readable and synchronous manner. We can use them to perform background tasks and they are a great way to perform network requests and long-running tasks such as reading and writing to a database. They do these tasks off the main thread and ensure that we don’t block our main thread while performing these operations. The main benefits of using coroutines are as follows:

  • They are lightweight and easy to use.
  • They have built-in cancellation support.
  • They lower the chances of apps having memory leaks.
  • As mentioned in earlier chapters, Jetpack libraries also support and use coroutines.

We have already added the core and Android coroutines libraries in our app. Let us understand some coroutines basics before proceeding to use coroutines in our project.

Coroutine basics

In this section, we will be looking at different...

Using Kotlin coroutines for network calls

In this section, we will refactor our repository to use coroutines. We will use StateFlow to emit data from ViewModel to the view layer. We will also use the Dispatchers.IO dispatcher to perform our network requests on a background thread.

Let us start by creating a NetworkResult sealed class, which will represent the different states of our network request:

sealed class NetworkResult<out T> {
    data class Success<out T>(val data: T) : NetworkResult<T>()
    data class Error(val error: String) : NetworkResult<Nothing>()
}

The NetworkResult class is a sealed class that has two subclasses. We have the Success data class that will be used to represent a successful network request. It has a data property that will be used to hold the data returned from the network request. We also have the Error class, which will be used to represent a failed network request. It has an error...

Summary

In this chapter, we learned how to perform network calls with Retrofit. Moreso, we learned how to take advantage of Kotlin coroutines to perform asynchronous network requests in our app and refactored our app to fetch some cute cats with Kotlin coroutines.

In the next chapter, we will be looking at another Jetpack library, Jetpack Navigation, to handle navigation in our app.

lock icon The rest of the chapter is locked
You have been reading a chapter from
Mastering Kotlin for Android 14
Published in: Apr 2024 Publisher: Packt ISBN-13: 9781837631711
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime}