Last active
May 20, 2019 19:42
-
-
Save AlexMisiulia/986225c6b62699f22d083bbae8fbd9be 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
@Target(AnnotationTarget.FUNCTION) | |
@kotlin.annotation.Retention(AnnotationRetention.RUNTIME) | |
@MapKey | |
annotation class ViewModelKey(val value: KClass<out ViewModel>) | |
@Module | |
abstract class ViewModelModule { | |
@Binds | |
@IntoMap | |
@ViewModelKey(MainViewModel::class) | |
abstract fun providesMainViewModel(mainViewModel: MainViewModel): ViewModel | |
} | |
@Singleton | |
class ViewModelFactory @Inject constructor(private val viewModels: MutableMap<Class<out ViewModel>, Provider<ViewModel>>) : | |
ViewModelProvider.Factory { | |
@Suppress("UNCHECKED_CAST") | |
override fun <T : ViewModel> create(modelClass: Class<T>): T { | |
val provider = viewModels[modelClass] | |
return if (provider != null) { | |
provider.get() as T | |
} else { | |
throw IllegalArgumentException("Can't find provider for ViewModel class ${modelClass.simpleName}") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment