Skip to content

Instantly share code, notes, and snippets.

@seisuke
Last active March 9, 2018 05:10
Show Gist options
  • Save seisuke/1bf03023767edc384477742cf889f6b2 to your computer and use it in GitHub Desktop.
Save seisuke/1bf03023767edc384477742cf889f6b2 to your computer and use it in GitHub Desktop.
Kotlin way ViewModelFactory with dagger2
import android.arch.lifecycle.ViewModel
import android.arch.lifecycle.ViewModelProvider
import javax.inject.Inject
import javax.inject.Provider
import javax.inject.Singleton
@Singleton
class ViewModelFactory @Inject constructor(
private val creators: Map<Class<out ViewModel>,
@JvmSuppressWildcards Provider<ViewModel>>
) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
val creator = creators[modelClass]
?: creators.entries.firstOrNull { (key, _) ->
modelClass.isAssignableFrom(key)
}?.value
?: throw IllegalArgumentException("unknown model class " + modelClass)
return creator.get() as T
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment