Koin – Add ViewModel module

Reading Time: 2 minutes
In the very last chapter we have refactored our code to use the Koin library. We have added a module, where we have set the data classes. Then we have created an application wide class, and finally we have refactored the viewmodel. So from now it contains less code then before. In this chapter we will create a module for the ViewModel as well.
The ViewModel class is designed to store and manage UI-related data in a lifecycle conscious way. The ViewModel class allows data to survive configuration changes such as screen rotations. (Android Developer: ViewModel Overview)

Step 1 – Add the dependency

Our first step will be to add the Koin’s ViewModel dependency to the App build.gradle. Here, in the previous chapter we have added the Koin library. The implementation of this dependency will be after that.

implementation “org.koin:koin-androidx-viewmodel:$koin_version

Click again on the Sync now link at the right top corner.

Step 2 – Add the ViewModel module

View models are injected as field injections. We can lazily inject the MainActivityViewModel::class to the MainActivity::class using the viewModel{} delegate. First open from the modul package, then the AppModuls::class. Here we have implemented already in the last chapter the appModul module. Now we will add for it the module of the viewModel. Inside of the curly brackets will be the MainActivityViewModel().


mainActivityViewModelModule

Now you can close the AppModul::class.

Step 3 – Refactoring the MainActivity::class

The last step is to refactor the instance of the ViewModel in our MainActivity::class. There we have currently a lazy implementation.


mainActivityViewModel 

Modify this line to have the instance from Koin


mainActivityViewModel with Koin

That’s it. We have added Koin’s ViewModel to our app, so run it and create a new order. It should work as before.

GitHub

You can find this code as well on GitHub under the AddViewModelModule branch.

GitHub – AddViewModelModule branch

Questions

I hope the description was understandable and clear. But if you have still questions, then leave me comments below! 😉 Have a nice a day! 🙂  


 

Follow and like us:
Click to rate this post!
[Total: 0 Average: 0]

Leave a comment

stay informed!

Subscribe to receive exclusive content and notifications