sil*_*ira 3 android dependency-injection mvvm viewmodel kotlin
我正在使用 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))
}
}
Run Code Online (Sandbox Code Playgroud)
我想知道是否有办法在 Kotlin 中做到这一点,因为我很确定我可以轻松地在 Java 中做到这一点。谢谢。
解决方案由 koin 团队在 version 中提供0.9.0-alpha-11,最终代码如下所示:
open class BaseActivity<out ViewModelType : BaseViewModel>(clazz: KClass<ViewModelType>) :
AppCompatActivity() {
val viewModel: ViewModelType by viewModel(clazz)
fun snackbar(message: String?) {
message?.let { longSnackbar(find(android.R.id.content), it) }
}
fun toast(message: String?) {
message?.let { longToast(message) }
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4291 次 |
| 最近记录: |