Created
March 27, 2020 14:48
-
-
Save osipxd/ad8bb71d00a943010cac3077c0bf80a2 to your computer and use it in GitHub Desktop.
Dagger ViewModel Multibinding
This file contains hidden or 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