Last active
September 16, 2017 22:04
-
-
Save alexfacciorusso/1d04e311ce61ea2b60e69ef489ddeb99 to your computer and use it in GitHub Desktop.
A Dagger 2 injected ViewModelProvider.Factory implementation.
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
@Singleton | |
class DaggerViewModelFactory | |
@Inject constructor( | |
private val creators: Map<Class<out ViewModel>, @JvmSuppressWildcards Provider<ViewModel>> | |
) : ViewModelProvider.Factory { | |
override fun <T : ViewModel> create(modelClass: Class<T>): T { | |
val creator = creators[modelClass] ?: | |
creators.asIterable().firstOrNull { modelClass.isAssignableFrom(it.key) }?.value | |
?: throw IllegalArgumentException("unknown model class " + modelClass) | |
return try { | |
creator.get() as T | |
} catch (e: Exception) { | |
throw RuntimeException(e) | |
} | |
} | |
} |
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
@Module | |
abstract class ViewModelFactoryModule { | |
@Binds | |
internal abstract fun bindViewModelFactory(factory: GithubViewModelFactory): ViewModelProvider.Factory | |
} |
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
@Target(AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER) | |
@MapKey | |
internal 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