hi guys!
i'm trying to migrate from Koin to Hilt
what is the best way to inject fields into the BaseViewModel?
i have such structure: MyViewModel extends BaseViewModel extends ViewModel
is it possible to inject directly into the fields/properties of BaseViewModel?
thanks. i saw it. so the only way to inject is via constructor?
a
Arun
06/15/2020, 1:11 PM
I would say that is the best practice. Member injection is possible but not recommended since it will cause tight coupling between Component and ViewModel.
@Inject and @Assisted on constructor is a good way to start
β 1
d
deviant
06/15/2020, 1:14 PM
Copy code
abstract class BaseViewModel() : ViewModel() {
@Inject
protected lateinit var prefs: Prefs
this doesn't work for me. and @ViewModelInject can't be applied on properties π
i don't care about tight coupling in current project. what i'm trying to do is leave base class constructor as clean as possible
abstract class BaseViewModel(val prefs: Prefs) : ViewModel
and subclass
Copy code
class HomeViewModel @Inject constructor(override val prefs: Prefs) : ViewModel()
π 1
d
deviant
06/15/2020, 1:25 PM
that's almost how i managed it eventually. i made the property abstract and override it in the child object constructor. thanks mate!
ππΌ 1
g
gildor
06/15/2020, 2:02 PM
Yes, itβs recommended approach with dagger, inject only top most class, do not inject abstract classes
c
Colton Idle
06/17/2020, 3:58 AM
@gildor I didn't know this. Thanks! Do you know if there's a reference to that claim? I would like to attach it to my PR where I'm going to remove @Inject ions into some base classes.