Book Image

How to Build Android Apps with Kotlin

By : Alex Forrester, Eran Boudjnah, Alexandru Dumbravan, Jomar Tigcal
Book Image

How to Build Android Apps with Kotlin

By: Alex Forrester, Eran Boudjnah, Alexandru Dumbravan, Jomar Tigcal

Overview of this book

Are you keen to get started building Android 11 apps, but don’t know where to start? How to Build Android Apps with Kotlin is a comprehensive guide that will help kick-start your Android development practice. This book starts with the fundamentals of app development, enabling you to utilize Android Studio and Kotlin to get started building Android projects. You'll learn how to create apps and run them on virtual devices through guided exercises. Progressing through the chapters, you'll delve into Android’s RecyclerView to make the most of lists, images, and maps, and see how to fetch data from a web service. Moving ahead, you'll get to grips with testing, learn how to keep your architecture clean, understand how to persist data, and gain basic knowledge of the dependency injection pattern. Finally, you'll see how to publish your apps on the Google Play store. You'll work on realistic projects that are split up into bitesize exercises and activities, allowing you to challenge yourself in an enjoyable and attainable way. You'll build apps to create quizzes, read news articles, check weather reports, store recipes, retrieve movie information, and remind you where you parked your car. By the end of this book, you'll have the skills and confidence to build your own creative Android applications using Kotlin.
Table of Contents (17 chapters)
Preface
12
12. Dependency Injection with Dagger and Koin

The Repository Pattern

Instead of the ViewModel directly calling the services for getting and storing data, it should delegate that task to another component, such as a repository.

With the Repository pattern, you can move the code in the ViewModel that handles the data layer into a separate class. This reduces the complexity of the ViewModel, making it easier to maintain and test. The repository will manage where the data is fetched and stored, just as if the local database or the network service were used to get or store data:

Figure 14.3: ViewModel with the Repository pattern

In your ViewModel, you can add a property for the repository:

class MovieViewModel(val repository: MovieRepository): ViewModel() {
... 
}

The ViewModel will get the movies from the repository, or it can listen to them. It will not know where you actually got the list from.

You can create a repository interface that connects to a data source, such as in the following example...