Skip to content

Instantly share code, notes, and snippets.

@AfzalivE
Created July 29, 2019 18:29
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 AfzalivE/7c363a955358d957d825f59b7d5618ee to your computer and use it in GitHub Desktop.
Save AfzalivE/7c363a955358d957d825f59b7d5618ee to your computer and use it in GitHub Desktop.
ViewModelFactory for Dagger2
/**
* Constructs a ViewModelFactory with dependencies
*/
@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 {
var creator = creators[modelClass]
if (creator == null) {
creator = creators.entries.firstOrNull {
return@firstOrNull modelClass.isAssignableFrom(it.key)
}?.value
if (creator == null) {
throw IllegalArgumentException("Unknown model class $modelClass, have you declared this class in ViewModelModule?")
}
}
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