Я хочу предоставить классы BaseMvRxViewModel с Dagger 2. Как я могу настроить ViewModel Factory и модуль кинжала для этого?
Я предоставлял классы ViewModel с Dagger 2, например:
ViewModelModule.kt
@Module
abstract class ViewModelModule {
@Binds
abstract fun bindViewModelFactory(factory: ViewModelFactory):
ViewModelProvider.Factory
@Binds
@IntoMap
@ViewModelKey(LevelsViewModel::class)
abstract fun bindLevelsViewModel(viewModel: LevelsViewModel):
ViewModel
}
ViewModelKey.kt
@MapKey
@Target(AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER)
@Retention(AnnotationRetention.RUNTIME)
annotation class ViewModelKey(val value: KClass<out ViewModel>)
ViewModelFactory.kt
@Singleton
class ViewModelFactory @Inject constructor(private val creators: Map<Class<out ViewModel>,
@JvmSuppressWildcards Provider<ViewModel>>) : ViewModelProvider.Factory {
@Suppress("UNCHECKED_CAST")
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)
}
}
}
LevelsFragment.kt
override fun onViewCreated(view: View, savedInstanceState: Bundle?)
{
super.onViewCreated(view, savedInstanceState)
viewModel = ViewModelProviders.of(activity, viewModelFactory)
.get(LevelsViewModel::class.java)
}