Skip to content

Instantly share code, notes, and snippets.

@Swisyn
Forked from osipxd/ViewModelFactory.kt
Created May 13, 2020 11:44
Show Gist options
  • Save Swisyn/394dbcce07628c74fd9b2580e9e001d6 to your computer and use it in GitHub Desktop.
Save Swisyn/394dbcce07628c74fd9b2580e9e001d6 to your computer and use it in GitHub Desktop.
Dagger ViewModel Multibinding
class ViewModelFactory @Inject constructor(
private val providers: Map<Class<out ViewModel>, @JvmSuppressWildcards Provider<ViewModel>>
) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
val provider = providers[modelClass]
?: providers.asIterable().find { modelClass.isAssignableFrom(it.key) }?.value
?: error("Unknown ViewModel class $modelClass")
return try {
@Suppress("UNCHECKED_CAST")
provider.get() as T
} catch (e: Exception) {
throw RuntimeException(e)
}
}
}
@Target(AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.RUNTIME)
@MapKey
annotation class ViewModelKey(val value: KClass<out ViewModel>)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment