Skip to content

Instantly share code, notes, and snippets.

@jpardogo
Last active August 20, 2018 19:56
Show Gist options
  • Save jpardogo/54820568222c19a8e3890878f4299b8e to your computer and use it in GitHub Desktop.
Save jpardogo/54820568222c19a8e3890878f4299b8e to your computer and use it in GitHub Desktop.
ViewModelBinder utility class for Kodein DI
inline fun <reified ViewModelT : ViewModel> BindActivity.viewModelBinder() = lazy {
activitybBinder<ViewModelT>(bindActivity = this)
}
inline fun <reified ViewModelT : ViewModel> BindFragment.viewModelBinder() = lazy {
ViewModelProviders
.of(this,
getFactory<ViewModelT>(kodein))
.get(ViewModelT::class.java)
}
inline fun <reified ViewModelT : ViewModel> BindFragment.viewModelActivityBinder() = lazy {
val bindActivity = activity as BindActivity
activitybBinder<ViewModelT>(bindActivity)
}
inline fun <reified ViewModelT : ViewModel> activitybBinder(bindActivity: BindActivity): ViewModelT {
return ViewModelProviders
.of(bindActivity,
getFactory<ViewModelT>(bindActivity.kodein))
.get(ViewModelT::class.java)
}
inline fun <reified ViewModelT : ViewModel> getFactory(
kodein: Kodein) =
object : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
@Suppress("UNCHECKED_CAST")
return Kodein {
extend(kodein)
}.run {
val viewModel by instance<ViewModelT>()
viewModel
} as T
}
}
//From any Activity extending from InjectedActivity
private val activityViewModel by viewModelBinder<MyActivityViewModel>()
override fun activityModule() = Kodein.Module(MyActivity.TAG) {
bind() from provider { MyActivityViewModel(instance(), instance()) }
}
//From any fragment extending from InjectedFragment
private val fragmentViewModel by viewModelBinder<MyFragmentViewModel>()
override fun fragmentModule() = Kodein.Module(MyFragment.TAG) {
bind() from provider { MyFragmentViewModel(instance()) }
}
//If you want to get activity ViewModel from the fragment
private val activityViewModel by viewModelActivityBinder<MyActivityViewModel>()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment