Injecting ViewModel — hard to easy

Comparing Dagger 2, Koin and Service Locator approaches

--

Picture by patrick lanza on Unsplash

Architecture Component ViewModel is the way to go for Android Development as advocated by the write up below.

However, there’s one pain point. ViewModel Injection.

To be exact, the pain is not the injection of ViewModel into Activity, but the injection of dependencies into ViewModel.

Let me elaborate.

If you want your ViewModel to be injected into Activity, it is as simple as doing the below

class MyActivity : AppCompatActivity() {    private val viewModel: MyViewModel by viewModels()    // ...
}

The viewModels() extension function is provided by androidx KTX . Even if the ViewModel has savedStateHandle or is taking the intent bundle from the Activity, it doesn’t need to be explicitly injected in. The viewModels() extension function does all that automatically behind the scene.

--

--