Shaun Plummer
01/18/2019, 10:51 AM@Binds
@IntoMap
@ViewModelKey(MyViewModel::class)
internal abstract fun bindMyViewModel(viewModel: MyViewModel): ViewModel
@Binds
internal abstract fun bindViewModelFactory(factory: ViewModelFactory): ViewModelProvider.Factory
@MustBeDocumented
@Target(
AnnotationTarget.FUNCTION,
AnnotationTarget.PROPERTY_GETTER,
AnnotationTarget.PROPERTY_SETTER
)
@Retention(AnnotationRetention.RUNTIME)
@MapKey
private annotation class ViewModelKey(val value: KClass<out ViewModel>)
@Suppress("UNCHECKED_CAST")
@Singleton
class ViewModelFactory @Inject constructor(
private val creators: Map<Class<out ViewModel>, @JvmSuppressWildcards Provider<ViewModel>>
) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
var creator = creators[modelClass]
if (creator == null) {
creator = creators
.entries
.firstOrNull { modelClass.isAssignableFrom(it.key) }?.value
?: throw IllegalArgumentException("unknown model class $modelClass")
}
return creator.get() as T
}
}
I'm not clear where inside my dagger setup I could be calling the fragment method.