Skip to content

Instantly share code, notes, and snippets.

@paulocns
Created August 4, 2018 21:59
Show Gist options
  • Save paulocns/34ebb4eb259962b7952e8afc9cd87ed2 to your computer and use it in GitHub Desktop.
Save paulocns/34ebb4eb259962b7952e8afc9cd87ed2 to your computer and use it in GitHub Desktop.
class ProjectViewModelFactory(viewModelSubComponent: ViewModelSubComponent) : ViewModelProvider.Factory {
private val creators: ArrayMap<Class<*>,() ->ViewModel> = ArrayMap()
init {
creators[HomeFragmentViewModel::class.java] = { viewModelSubComponent.homeFragmentViewModel() }
creators[QueryViewModelArc::class.java] = { viewModelSubComponent.queryViewModelArc() }
}
override fun <T : ViewModel> create(modelClass: Class<T>): T {
var creator: (() ->ViewModel)? = creators[modelClass]
if (creator == null) {
for ((key, value) in creators) {
if (modelClass.isAssignableFrom(key)) {
creator = value
break
}
}
}
if (creator == null) {
throw IllegalArgumentException("Unknown model class $modelClass")
}
try {
return creator.invoke()as T
} catch (e: Exception) {
throw RuntimeException(e)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment