ViewModel
The koin-android-viewmodel
introduces a new viewModel
DSL keyword that comes in complement of single
and factory
, to help declare a ViewModel
component and bind it to an Android Component lifecycle.
Your declared component must at least extends the android.arch.lifecycle.ViewModel
class. You can specify how you inject the constructor of the class
and use the get()
function to inject dependencies.
info
The
viewModel
keyword helps declaring a factory instance of ViewModel. This instance will be handled by internal ViewModelFactory and reattach ViewModel instance if needed.The
viewModel
keyword can also let you use the injection parameters.
Injecting your ViewModel
To inject a ViewModel in an Activity
, Fragment
or Service
use:
by viewModel()
- lazy delegate property to inject a ViewModel into a propertygetViewModel()
- directly get the ViewModel instance
In a similar way, in Java you can inject the ViewModel instance, but using viewModel()
or getViewModel
static functions from ViewModelCompat
:
note
ViewModel API is accessible from Koin & Scope instances. But also from ViewModelStoreOwner
class
Shared ViewModel
One ViewModel instance can be shared between Fragments and their host Activity.
To inject a shared ViewModel in a Fragment
use:
by sharedViewModel()
- lazy delegate property to inject shared ViewModel instance into a propertygetSharedViewModel()
- directly get the shared ViewModel instance
Just declare the ViewModel only once:
Note: a qualifier for a ViewModel will be handled as a ViewModel's Tag
And reuse it in Activity and Fragments:
info
The Activity sharing its ViewModel injects it with by viewModel()
or getViewModel()
. Fragments are reusing the shared ViewModel with by sharedViewModel()
.
For your Java Fragment, must be used sharedViewModel
or getSharedViewModel
from SharedViewModelCompat
.
ViewModel and injection parameters
the viewModel
keyword and injection API is compatible with injection parameters.
In the module:
or even
In the module:
From the injection call site:
ViewModel and State Bundle
Add a new property typed SavedStateHandle
to your constructor to handle your ViewModel state:
In Koin module, just resolve it with get()
:
Just call your ViewModel:
You can even pass a bundle data as your state argument. Use the state
property like follow:
note
StateViewModel API is accessible from Koin & Scope instances.