Android Koin scope and Context

Koin scope

In the previous entry, I explained about simple usage of Koin. (Android Koin Get Started)

In this time, I explain scope and context

Scope is lifecycle of injection object. (range to live object)

To set scope, we can decide lifetime for injection object

Example

  • HelloScopeRepository
  • HelloScopeRepositoryImpl
  • ScopePresentor
  • modules.kt
  • MainActivity.kt

For build.gradle please check previous entry

HelloScopeRepository

interface HelloScopeRepository {

    fun giveHello(): String
}

HelloScopeRepositoryImpl

class HelloScopeRepositoryImpl() : HelloScopeRepository {
    override fun giveHello() = "Hello Koin"
}

ScopePresentor

class ScopePresenter(val repo: HelloScopeRepository) {

    fun sayHello() = "${repo.giveHello()} from $this"
}

modules.kt

val appModule = module {
   single<HelloScopeRepository> { HelloScopeRepositoryImpl() }
   scope(named<MainActivity>()) {
        scoped { ScopePresenter(get()) }
   }
}

Now, ScopePresenter becomes scope injection under MainActivity

MainActivity

class MainActivity : AppCompatActivity() {
    val scopedPresenter : ScopePresenter by lifecycleScope.inject()

    val contextRepository : HelloContextRepository by inject() // No Context

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val greeting4 = scopedPresenter.sayHello()
        print(greeting4)

        val name = contextRepository.getName()
        print(name)
    }
}

Context

We want to use Context when we generate object using injection.

Koin supports those kind of situation.

modules.kt

import org.koin.android.ext.koin.androidContext
val appModule = module {
   // Context
    single<HelloContextRepository> { HelloContextRepositoryImpl(androidContext()) }
}

HelloContextRepository

interface HelloContextRepository {
    fun getName() : String
}

HelloContextRepositoryImpl

class HelloContextRepositoryImpl : HelloContextRepository {

    private lateinit var appContext: Context

    override fun getName() : String {
        return appContext.getString(R.string.app_name)
    }

    constructor(context: Context) {
        appContext = context.applicationContext
    }
}
Android
スポンサーリンク
Professional Programmer2

コメント