Koin是一款輕量級的依賴注入框架肮韧,根據(jù)官方的描述融蹂,它無代理旺订,無代碼生成,無反射超燃。
學(xué)過Dagger2的同學(xué)都深深體會到Dagger入門的艱辛区拳。
但是Koin,你通過5分鐘的學(xué)習(xí)就可以掌握它的基本用法意乓。
學(xué)完Koin樱调,你可以向Dagger 說bye bye了。
第一步:Gradle Setup
在你的app build.gradle中添加依賴:
// Add Jcenter to your repositories if needed
repositories {
jcenter()
}
dependencies {
// Koin for Android
compile "org.koin:koin-android:1.0.1"
// Koin Android Scope feature
compile "org.koin:koin-android-scope:1.0.1"
// Koin Android ViewModel feature
compile "org.koin:koin-android-viewmodel:1.0.1"
}
第二步:Our components
寫一些測試用的類届良,提供數(shù)據(jù)
interface HelloRepository {
fun giveHello(): String
}
class HelloRepositoryImpl() : HelloRepository {
override fun giveHello() = "Hello Koin"
}
第三步:自定義ViewModel
使用第二步定義類提供的數(shù)據(jù)
class MyViewModel(val repo : HelloRepository) : ViewModel() {
fun sayHello() = "${repo.giveHello()} from $this"
}
第四步:定義Koin module
val appModule = module {
// single instance of HelloRepository
single<HelloRepository> { HelloRepositoryImpl() }
// MyViewModel ViewModel
viewModel { MyViewModel(get()) }
}
代碼分析:
- appModule中聲明了MyViewModel笆凌,它的參數(shù)傳入了get(), 它將自動搜索到對應(yīng)的HelloRepository,創(chuàng)建實例士葫。
- single標(biāo)明HelloRepository創(chuàng)建的是單例
第五步:啟動 Koin
class MyApplication : Application(){
override fun onCreate() {
super.onCreate()
// Start Koin
startKoin(this, listOf(appModule))
}
}
第六步:注入依賴
class MyViewModelActivity : AppCompatActivity() {
// Lazy Inject ViewModel
val myViewModel: MyViewModel by viewModel()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_simple)
//...
}
}
總結(jié)
通過上述幾步乞而,我們實現(xiàn)了自定義module的依賴注入琼富,代碼非常簡單费彼,易于理解绘闷。
本文基于Koin的1.0.1版本分析寇漫。
值得注意的是Koin針對Java郊艘,Android齿穗,和AndriodX的依賴庫是不一樣阵难,需要根據(jù)你的實際需求添加舅列,詳見
https://insert-koin.io/docs/1.0/setup/
如果你需要了解更多信息鞋喇,請參考:
https://insert-koin.io/docs/1.0/getting-started/introduction/
https://insert-koin.io/docs/1.0/quick-references/koin-dsl/
官網(wǎng):
https://insert-koin.io/