Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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 {
inline fun <reified ViewModelT : ViewModel> BindFragment.viewModelActivityBinder() = lazy {
val bindActivity = activity as BindActivity
inline fun <reified ViewModelT : ViewModel> activitybBinder(bindActivity: BindActivity): ViewModelT {
return ViewModelProviders
inline fun <reified ViewModelT : ViewModel> getFactory(
kodein: Kodein) =
object : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return Kodein {
}.run {
val viewModel by instance<ViewModelT>()
} 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