-
-
Save Swisyn/394dbcce07628c74fd9b2580e9e001d6 to your computer and use it in GitHub Desktop.
Dagger ViewModel Multibinding
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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