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:
Use the following code to create an extention method for FragmentActivity
:
Use the this code to create an extension method for Fragment
:
Eager mode
You can still initiate a ViewModel
eagerly when you write:
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.