Hello Elye, what a great article! Thanks for the good comparison and code samples to study.
I normally follow the dagger-android approach for two reasons:
1 . I’ve a template that helps me with the boilerplate (but still we need to repeat a few lines for every ViewModel)
2 . I hate having public dependencies :/
I have two question for you:
- What approach you would follow in large projects if you had to choose between the dagger approaches? Let’s assume we have a template that removes the first drawback (complicated setup). We still have 2 left :(
- I have a major drawback in my template. Following your sample, I don’t have a MyViewModelFactory class that injects the repository instead I’ve this:
class ViewModelFactory @Inject constructor(
private val viewModelMap: MutableMap<Class<out ViewModel>, ViewModelAssistedFactory<out ViewModel>>,
owner: SavedStateRegistryOwner,
defaultArgs: Bundle?
) : AbstractSavedStateViewModelFactory(owner, defaultArgs) {
@Throws(IllegalStateException::class)
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel?> create(key: String, modelClass: Class<T>, handle: SavedStateHandle): T {
return viewModelMap[modelClass]?.create(handle) as? T ?: throw IllegalStateException("Unknown ViewModel class")
}
}
interface ViewModelAssistedFactory<T : ViewModel> {
fun create(stateHandle: SavedStateHandle): T
}
ActivityModule would be:
@Module
abstract class SplashActivityModule : BaseActivityModule<SplashActivity>() {
@Binds
@IntoMap
@ViewModelKey(SplashViewModel::class)
abstract fun bindFactory(factory: SplashViewModel.Factory): ViewModelAssistedFactory<out ViewModel>
companion object {
@Nullable
@Provides
fun provideDefaultArgs(): Bundle? {
return null
}
}
}
And my BaseActivity:
@Inject
lateinit var viewModelFactory: ViewModelFactory
protected val viewModel: ViewModel by lazy { ViewModelProvider(this, viewModelFactory).get(getViewModelClass()) }
And here lies my problem. I can’t have this: intent.extras… :|
private val viewModel: MyViewModel by viewModels { GenericSavedStateViewModelFactory(viewModelFactory, this, intent.extras) }
Because my ViewModelFactory dependencies are injected. Do I have other alternative to solve this problem or do I have to make does dependencies not injected?
Thanks for your time, cheers!