Member-only story

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.

--

--

Mobile App Development Publication
Mobile App Development Publication

Published in Mobile App Development Publication

Sharing iOS, Android and relevant Mobile App Development Technology and Learning

Elye - A One Eye Dev By His Grace
Elye - A One Eye Dev By His Grace

Written by Elye - A One Eye Dev By His Grace

Sharing Software Learning, Life and Faith Journey

Responses (2)

What are your thoughts?