Guilherme Delgado
1 min readNov 29, 2019

Ok I found out what was missing. So my approach was right (and it is similar to yours but more generic), thing is, in my BaseActivity:

abstract class BaseActivity<ViewBinding : ViewDataBinding, ViewModel : BaseViewModel> : AppCompatActivity(), HasAndroidInjector {

@Inject
lateinit var dispatchingAndroidInjector: DispatchingAndroidInjector<Any>
@Inject
lateinit var viewModelFactory: ViewModelFactory
protected val viewModel: ViewModel by lazy { ViewModelProvider(this, viewModelFactory).get(getViewModelClass()) }
protected val binding
: ViewBinding by lazy { DataBindingUtil.setContentView<ViewBinding>(this, getLayoutResId()) }
...

I’m providing a Factory just for the ViewModel received by parameter from the ChildActivity. To be able to use N ViewModels, it’s ChildActivity responsibility to provide them just like the Base does.

I also have a generic ViewModelFactory:

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")
}
}

A generic ViewModelAssitedFactory:

interface ViewModelAssistedFactory<T : ViewModel> {
fun create(stateHandle: SavedStateHandle): T
}

And every ViewModel just have to add this lines:

@AssistedInject.Factory
interface Factory : ViewModelAssistedFactory<MyViewModel>

The rest will be handled by Dagger :)

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 🏄‍♂️

No responses yet

Write a response