Android ViewModel — Manual Dependency Injection Made Easy

Remove some boiler plate and make manual dependency injection with Android View Models easier with the power of Kotlin extensions.

Image for post
Image for post
Photo by Toan Chu https://unsplash.com/@toanchu90 on Unsplash

Lazy DI Using Android Lifecycle ViewModel Extensions

One of the ways the Android Fragment & Lifecycle teams have tried to make the View Model easier to use in Activities and Fragments is providing the Android Lifecycle ViewModel Kotlin Extensions library.

View Model Provider Factory

One way to enable this behavior is to use ViewModelProvider.Factory, with which you can instantiate a View Model with it’s needed dependencies. To do so, you need to create your own Factory that extends the ViewModelProvider.Factory interface, or create a function that can return an object that overrides the Factory.create method.

View Model Provider & Kotlin Extension Mashup

Remember, we could use by viewModels or by activityViewModels to delegate the creation of our View Models, but we weren’t able to inject our required dependencies without a Factory.

Endgame: Easy View Model DI

Let’s use the power of extension functions, our Factory knowledge, and the ViewModelLazy class to delegate the creation of our View Model to functions on Activity and Fragment.

Written by

Mobile developer and designer. Into the Jamstack. Read on at ajkueterman.dev

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store