Created
April 11, 2020 12:12
-
-
Save pavlospt/908c47fd554012369382bf33dffacbfc to your computer and use it in GitHub Desktop.
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
@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