Search code examples
androidandroid-viewmodelkoin

How to have 2 instances of parametrized sharedViewModel?


val viewModel: StuffViewModel by sharedViewModel { parametersOf(arguments.id) }

Now, when I have multiple instanec of the same Fragment class, how can I have new instance for each of it? I thought that's what parametersOf() does, but it doesn't seem to be true.

And yes, it has to be sharedViewModel, because of some logic which causes some complex fragment manipulation and the viewmodels are binding to services, and it seems like a better idea to just have shared instances instead of recreating them and rebinding the service every time.

What I want:

/---------Activity---------\
|                          |
|     StuffViewModel(1)    |
|     StuffViewModel(2)    |
|                          |
| /---StuffFragment(1)---\ |
| |                      | |
| |  *StuffViewModel(1)  | |
| |                      | |
| \----------------------/ |
|                          |
| /---StuffFragment(2)---\ |
| |                      | |
| |  *StuffViewModel(2)  | |
| |                      | |
| \----------------------/ |
|                          |
\--------------------------/

What I get:

/---------Activity---------\
|                          |
|     StuffViewModel(1)    |
|                          |
| /---StuffFragment(1)---\ |
| |                      | |
| |  *StuffViewModel(1)  | |
| |                      | |
| \----------------------/ |
|                          |
| /---StuffFragment(2)---\ |
| |                      | |
| |  *StuffViewModel(1)  | |
| |                      | |
| \----------------------/ |
|                          |
\--------------------------/

Solution

  • We didn't find any toher solution then to have separate ViewModel instances.