【发布时间】:2018-07-24 10:57:21
【问题描述】:
我正在使用 Kotlin 和 Android 架构组件(ViewModel、LiveData)构建新的 Android 应用程序的架构,并且我还使用 Koin 作为我的依赖注入提供程序。
问题是我无法通过 koin 注入在 BaseActivity 中以通用方式初始化 ViewModel。当前代码如下所示:
abstract class BaseActivity<ViewModelType : ViewModel> : AppCompatActivity() {
// This does not compile because of the generic type
private val viewModel by lazy {
// Koin implementation to inject ViewModel
getViewModel<ViewModelType>()
}
@CallSuper
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Fabric.with(this, Crashlytics())
}
/**
* Method needed for Calligraphy library configuration
*/
@CallSuper
override fun attachBaseContext(newBase: Context) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase))
}
}
我想知道是否有办法在 Kotlin 中做到这一点,因为我很确定我可以轻松地在 Java 中做到这一点。 谢谢。
【问题讨论】:
标签: android mvvm dependency-injection kotlin viewmodel