Skip to content

Instantly share code, notes, and snippets.

@ferazog
Created October 22, 2021 17:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ferazog/25ca6257e5e9e63c2a12c1271f19a87f to your computer and use it in GitHub Desktop.
Save ferazog/25ca6257e5e9e63c2a12c1271f19a87f to your computer and use it in GitHub Desktop.
class ViewModelFactory @Inject constructor(
private val viewModelsMap: Map<Class<out ViewModel>, @JvmSuppressWildcards Provider<ViewModel>>
) : ViewModelProvider.Factory {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
val creator = viewModelsMap[modelClass] ?: viewModelsMap.asIterable().firstOrNull {
modelClass.isAssignableFrom(it.key)
}?.value ?: throw IllegalArgumentException("unknown model class $modelClass")
try {
@Suppress("UNCHECKED_CAST")
return creator.get() as T
} catch (e: Exception) {
throw RuntimeException()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment