Koin is a dependency injection library written in pure Kotlin

How to manage dependency injection with a time scope mechanism

For future students of the course "Android Developer. Professional" prepared a translation of a useful article.

We also invite you to take part in the open webinar on the topic "Writing a Gradle plugin"


What is this article about

You will learn how to use Koin modules to limit survivability of component-specific dependencies. You will also learn about standard Koin scopes and how to work with custom scopes.

Introduction

Android developers do not recommend using Dependency Injection (DI) if your application has three or fewer screens. But if there are more of them, it is better to use DI.

A popular way to implement DI in Android applications is based on the Dagger framework. But it requires deep study. One of the best alternatives to this framework is Koin, a library written in pure Kotlin.

Dagger DI, , , , (scope). , ,  — . .

Koin

Koin Android. , , (ViewModel) , .

, Koin .

  • single ( ) —  , ( );

  • factory ( ) — , ( );

  • scoped ( ) — , .

Single object.  Factory of objects (factory)
(single). (factory)

single , factory .

single factory Koin Koin. .

. , OnBoardRepository Android- . , .

Koin, API . Koin . .

1

, . CustomScope. . :

creating custom koin scope

2

single factory . . :

dependencies inside custom scopes

3

Koin. , . Android-, Activity, Fragment . .

, Koin, createScope, .

val stringQualifiedScope = getKoin().createScope(    
  "ScopeNameID", named("CustomeScope"))

CustomScope , Koin , Koin. ScopeNameID — , , . .

Android-, createScope getOrCreateScope. , .

4

, , . . .

val sampleClass = stringQualifiedScope.get<SampleClass>(        
qualifier = named("scopedName"))

scopedName factoryName — , Koin  2.

5

, stringQualifiedScope,   sampleclass, close. , , close onDestroy. :

override fun onDestroy() {
    super.onDestroy()
    stringQualifiedScope.close()
}

Koin-Android

. , Koin. Android-, Koin , , .

Koin-Android. dependencies build.gradle :

// Koin for Android
implementation "org.koin:koin-android:$koin_version"
// Koin Android Scope features
implementation "org.koin:koin-android-scope:$koin_version"

Koin-Android

, , onDestroy Android. Koin lifecyclescope.

Koin Android. :

val androidModule = module {

    scope<SampleActivity> {
        scoped { SampleClass() }
    }
  
}

scoping dependency with android activity

lifecyclescope:

val sampleClass : SampleClass by lifecycleScope.inject()

, . :

@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)    
fun onDestroy() {
    if (event == Lifecycle.Event.ON_DESTROY) {       
        scope.close()
        }
    }
}

, . , , . , .

. , - . !


"Android Developer. Professional". " Gradle plugin" .




All Articles