Lazy initialization of ViewModel (simple topic)
This article will explain how to initialize a ViewModel
using the simplest syntax that has occurred to me so far.
It is the follow-up to another one in which I already wrote about lazy initialization of ViewModel
.
This time I believe I found a simpler solution. I use it in my projects Victor-Events and Wiktor-Navigator.
When you apply this solution, you will only have to write the following code to initialize a ViewModel
lazily:
private val eventsModel by viewModel<EventsViewModel>()
Use the following code to create an extention method for FragmentActivity
:
inline fun <reified R : ViewModel> FragmentActivity.viewModel() = lazy { getViewModel<R>() }
inline fun <reified R : ViewModel> FragmentActivity.getViewModel() =
ViewModelProviders.of(this).get(R::class.java)
Use the this code to create an extension method for Fragment
:
inline fun <reified R : ViewModel> Fragment.viewModel() = lazy { getViewModel<R>() }
inline fun <reified R : ViewModel> Fragment.getViewModel() = activity!!.getViewModel<R>()
Eager mode
You can still initiate a ViewModel
eagerly when you write:
val eventsModel = getViewModel<EventsViewModel>()
Conclusion
This article demonstrates how to use the lazy()
function to for lazy initialization of a ViewModel
.
It also demonstrates how to create an extension function that can be used as an initializer passed as a lambda to lazy()
, so you can instantiate a class both ways.