Guilherme Delgado
2 min readApr 20, 2020

--

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:

  1. 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 :(
  2. 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!

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Guilherme Delgado
Guilherme Delgado

Written by Guilherme Delgado

Software Engineer at BlissApplications 🇵🇹 • github.com/GuilhE • When I’m not coding I’m 🧗🏽or 🏄‍♂️

Responses (1)

Write a response