把玩Kotlin依赖注入框架Koin

作者: 蓝不蓝编程 | 来源:发表于2019-04-19 10:39 被阅读6次

简要介绍

Koin是一个Kotin极轻量的依赖注入框架,据官方资料显示,它无代理,无代码生成,无反射。

把玩手法

  1. 添加依赖
//Koin for android
implementation "org.koin:koin-android:2.0.0-rc-1"
//Koin for scope feature
implementation "org.koin:koin-android-scope:2.0.0-rc-1"
//Koin for viewModel feature
implementation "org.koin:koin-android-viewmodel:2.0.0-rc-1"
  1. 添加正常的业务逻辑相关类(与Koin无关)
interface UserRepo {
    fun getName(): String
}
class UserRepoImpl : UserRepo {
    override fun getName(): String {
        return "jerry"
    }
}
class UserPresenter(val repo: UserRepo) {
    fun sayHi() = "Hi,${repo.getName()}"
}
  1. 添加module(敲黑板啦,伴侣关系就是在这里建立的,相守一生,哈哈)
val appModule = module {
    single<UserRepo> { UserRepoImpl() }
    factory { UserPresenter(get()) }
}
  1. 通知boss,初始化
class App : Application() {
    override fun onCreate() {
        super.onCreate()
        startKoin {
            androidLogger()
            androidContext(this@App)
            modules(appModule)
        }
    }
}
  1. 随便玩
  • 玩法一
class MainActivity : AppCompatActivity() {
    private val userPresenter: UserPresenter by inject()
    override fun onCreate(savedInstanceState: Bundle?) {
        val msg = userPresenter.sayHi()
    }
}
  • 玩法二,随便get都行
val userPresenter: UserPresenter = get()
val msg = userPresenter.sayHi()

Demo源代码

https://github.com/cxyzy1/koinDemo

介绍完毕,诸君随意.

附录

官网介绍: https://beta.insert-koin.io/docs/2.0/getting-started/introduction/

安卓开发技术分享: https://www.jianshu.com/p/442339952f26
点击关注专辑,查看最新技术分享
更多技术总结好文,请关注:「程序园中猿」

相关文章

网友评论

    本文标题:把玩Kotlin依赖注入框架Koin

    本文链接:https://www.haomeiwen.com/subject/kdafgqtx.html