Skip to content

Instantly share code, notes, and snippets.

@pavlospt
Created April 11, 2020 12:12
Show Gist options
  • Save pavlospt/908c47fd554012369382bf33dffacbfc to your computer and use it in GitHub Desktop.
Save pavlospt/908c47fd554012369382bf33dffacbfc to your computer and use it in GitHub Desktop.
@Suppress("UNCHECKED_CAST")
class ViewModelFactory @Inject constructor(
private val creators: Map<Class<out ViewModel>, Provider<ViewModel>>
) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
val creator = creators[modelClass]
?: creators.asIterable().find { (key, _) -> modelClass.isAssignableFrom(key) }?.value
?: throw IllegalArgumentException("Unknown ViewModel class $modelClass")
return try {
creator.get() as T
} catch (cce: ClassCastException) {
throw cce
}
}
}
@Module
object ViewModelFactoryModule {
@Provides
fun provideViewModelFactory(
viewModelMap: Map<Class<out ViewModel>, @JvmSuppressWildcards Provider<ViewModel>>
): ViewModelProvider.Factory = ViewModelFactory(creators = viewModelMap)
}
@Module
abstract class ViewModelModule {
@Binds
@IntoMap
@ViewModelKey(OurViewModel::class)
abstract fun bindsOurViewModel(ourViewModel: OurViewModel): ViewModel
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment