Skip to content

Instantly share code, notes, and snippets.

@mladenrakonjac
Created February 4, 2018 22:11
Show Gist options
  • Save mladenrakonjac/30f66e255c8456f08722d39f19c96459 to your computer and use it in GitHub Desktop.
Save mladenrakonjac/30f66e255c8456f08722d39f19c96459 to your computer and use it in GitHub Desktop.
class DaggerAwareViewModelFactory @Inject constructor(
private val creators: @JvmSuppressWildcards Map<Class<out ViewModel>, Provider<ViewModel>>
) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
var creator: Provider<out 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 {
@Suppress("UNCHECKED_CAST")
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