https://kotlinlang.org logo
#dagger
Title
# dagger
d

deviant

06/15/2020, 1:07 PM
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?
a

Arun

06/15/2020, 1:08 PM
Newly released Hilt is the recommended way for ViewModel injections. Guides are here https://developer.android.com/training/dependency-injection/hilt-jetpack
d

deviant

06/15/2020, 1:09 PM
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
a

Arun

06/15/2020, 1:20 PM
You can avoid @Inject in the base classes and just use @Inject in the deriving classes. A guide to this is here https://proandroiddev.com/clean-dagger-f248eda5790b Basically:
Copy code
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.
103 Views