Skip to content

Instantly share code, notes, and snippets.

@tolmachevroman
Last active November 26, 2017 05:14
Show Gist options
  • Save tolmachevroman/b5f407b960db5dc3cc6f469cb8441163 to your computer and use it in GitHub Desktop.
Save tolmachevroman/b5f407b960db5dc3cc6f469cb8441163 to your computer and use it in GitHub Desktop.
Medium Post 2. ViewModelFactory
@Singleton
class ViewModelFactory @Inject constructor(private val creators: Map<Class<out ViewModel>, @JvmSuppressWildcards Provider<ViewModel>>?) : ViewModelProvider.Factory {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
var creator = creators!![modelClass]
if (creator == null) {
for (entry in creators.entries) {
if (modelClass.isAssignableFrom(entry.key)) {
creator = entry.value
break
}
}
}
if (creator == null) {
throw IllegalArgumentException("unknown model class " + modelClass)
}
try {
return creator.get() 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