How To Use ViewModels Delegate With Constructor Parameters and Koin Dependency Injection
Save unnecessary code for loading data with bundle arguments.
The Kotlin viewModels
delegate lets us initialize our ViewModel
in our Android app’s activities or fragments with no effort.
However, the drawback of this function is that we are limited to the initialization of our respective ViewModel
without the ability to use any initial parameters via a constructor.
The problem
Because in many cases we have parameters that get passed by a previous screen via Navigation Component’s safe args or on the standard way via the arguments or intent bundle, we often need these parameters in our ViewModel
.
If we show a list on our screen that depends on the respective parameters for defining the query, we have no chance to pre-load data at the time of ViewModel
initialization.
By using the standard viewModels
delegate approach, we have to call a function that takes these parameters from our arguments and then loads the data.
Another drawback is that we have to make sure that our arguments restore the saved instance in the event of reloading the screen.