Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
How to Build Android Apps with Kotlin

You're reading from  How to Build Android Apps with Kotlin

Product type Book
Published in Feb 2021
Publisher Packt
ISBN-13 9781838984113
Pages 794 pages
Edition 1st Edition
Languages
Authors (4):
Alex Forrester Alex Forrester
Profile icon Alex Forrester
Eran Boudjnah Eran Boudjnah
Profile icon Eran Boudjnah
Alexandru Dumbravan Alexandru Dumbravan
Profile icon Alexandru Dumbravan
Jomar Tigcal Jomar Tigcal
Profile icon Jomar Tigcal
View More author details

Table of Contents (17) Chapters

Preface
1. Creating Your First App 2. Building User Screen Flows 3. Developing the UI with Fragments 4. Building App Navigation 5. Essential Libraries: Retrofit, Moshi, and Glide 6. RecyclerView 7. Android Permissions and Google Maps 8. Services, WorkManager, and Notifications 9. Unit Tests and Integration Tests with JUnit, Mockito, and Espresso 10. Android Architecture Components 11. Persisting Data 12. Dependency Injection with Dagger and Koin 13. RxJava and Coroutines 14. Architecture Patterns 15. Animations and Transitions with CoordinatorLayout and MotionLayout 16. Launching Your App on Google Play

12. Dependency Injection with Dagger and Koin

Overview

This chapter covers the concept of dependency injection and the benefits it provides to an Android application. We will look at how we can perform dependency injection manually with the help of container classes. We will also cover some of the frameworks available for Android, Java, and Kotlin that can help developers when it comes to applying this concept. By the end of this chapter, you will be able to use Dagger and Koin to manage your app's dependencies, and you will know how to organize them efficiently.

Introduction

In the previous chapter, we looked at how to structure code into different components, including ViewModels, repositories, API components, and persistence components. One of the difficulties that always emerged was the dependencies between all of these components, especially when it came to how we approached the unit tests for them.

We have constantly used the Application class to create instances of these components and pass them in the constructors of the components one layer above (we created the API and Room instances, then the Repository instances, and so on). What we were doing was a simplistic version of dependency injection.

Dependency injection (DI) is a software technique in which one object (application) supplies the dependencies of another object (repositories, ViewModels). The reason for this is to increase the reusability and testability of the code and to shift the responsibility for creating instances from our components to the Application class...

Manual DI

In order to understand how DI works, we can first analyze how we can manually inject dependencies into different objects across an Android application. This can be achieved by creating container objects that will contain the dependencies required across the app. You can also create multiple containers representing different scopes that are required across the application. Here, you can define dependencies that will only be required as long as a particular screen is displayed, and when the screen is destroyed, the instances can also be garbage collected.

A sample of a container that will hold instances as long as an application lives is shown here:

class AppContainer(applicationContext:Context) {
    val myRepository: MyRepository
    init {
        val retrofit =           Retrofit.Builder().baseUrl("https://google.com/").build()
        ...

Dagger

Dagger offers a comprehensive way to organize your application's dependencies. It has the advantage of being adopted first on Android by the developer community before Kotlin was introduced. This is one of the reasons that many Android applications use Dagger as their DI framework. Another advantage the framework holds is for Android projects written in Java, because the library is developed in the same language. The framework was initially developed by Square (Dagger 1) and later transitioned to Google (Dagger 2). We will cover Dagger 2 in this chapter and describe its benefits. Some of the key functionalities Dagger 2 provides are the following:

  • Injection
  • Dependencies grouped in modules
  • Components used to generate dependency graphs
  • Qualifiers
  • Scopes
  • Subcomponents

Annotations are the key elements when dealing with Dagger, because it generates the code required to perform the DI through an annotation processor. The main annotations can...

Koin

Koin is a lighter framework that is suitable for smaller apps. It requires no code generation and is built based on Kotlin's functional extensions. It is also a Domain Specific language (DSL). You may have noticed that when using Dagger, there's a lot of code that must be written in order to set up the DI. Koin's approach to DI solves most of those issues, allowing faster integration.

Koin can be added to your project by adding the following dependency to your build.gradle file:

implementation 'org.koin:koin-android:2.2.0-rc-4'

In order to set up Koin in your application, you need the startKoin call with the DSL syntax:

class MyApplication : Application() {
    override fun onCreate() {
        super.onCreate()
        startKoin {
            androidLogger(Level.INFO)
   ...

Summary

In this chapter, we analyzed the concept of DI and how it should be applied in order to separate concerns and prevent objects from having the responsibility of creating other objects and how this is of great benefit for testing. We started the chapter by analyzing the concept of manual DI. This served as a good example of how DI works and how it can be applied to an Android application; it served as the baseline when comparing the DI frameworks.

We also analyzed two of the most popular frameworks that help developers with injecting dependencies. We started with a powerful and fast framework in the form of Dagger 2, which relies on annotation processors to generate code to perform an injection. We also looked into Koin, which is a lightweight framework written in Kotlin with slower performance but a simpler integration and a lot of focus on Android components.

The exercises in this chapter were intended to explore how the same problem can be solved using multiple...

lock icon The rest of the chapter is locked
You have been reading a chapter from
How to Build Android Apps with Kotlin
Published in: Feb 2021 Publisher: Packt ISBN-13: 9781838984113
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 £13.99/month. Cancel anytime}