8

I have single activity application and number of fragments. Some of these fragments are using my viewmodel, typically like this:

private val myViewModel: MyViewModel by sharedViewModel()

What if I want to have the model both shared and keep its state with SavedStateHandle? I cannot figure out if this is supported and if so, how it needs to be used (declaring viewmodel as stateViewModel in hosting activity is not working).

ror
  • 3,295
  • 1
  • 19
  • 27

1 Answers1

12

Update: as koin 2.1.6 is around, they introduced org.koin.androidx.viewmodel.ext.android.stateSharedViewModel that you can use in your fragments.


Ok after an hour of digging Koin samples and figuring out a few gotchas:

  1. Assuming your view model is something similar to this:
class SavedStateViewModel(val handle: SavedStateHandle, val service: SimpleService) 
  1. ...and your DI looks like this:
viewModel { (handle: SavedStateHandle) -> SavedStateViewModel(handle, get()) }
  1. Your shared state view model can be consumed in your fragments like this:
val sharedSaved: SavedStateViewModel by sharedViewModel()
  1. (important!) You need this declaration in your activity:
lateinit var savedVm: SavedStateViewModel
  1. (important) You need to call this right after super.onCreate(savedInstanceState) in your activity:
savedVm  = getStateViewModel() 

It is important not to use lazy version for the above (stateViewModel).

ror
  • 3,295
  • 1
  • 19
  • 27
  • have you worked koin multi module in android app project – Edgar Apr 20 '20 at 21:39
  • nope. for clean architecture stuff? yes, but it's no fit (too complicated, few benefits) for most of the real life projects. overhyped! – ror Apr 21 '20 at 19:25
  • 1
    Wouldn't you also have to inject the saved state handle in the activity? How can the activity create a `SavedStateViewModel` without passing the handle as a parameter – 11m0 Jan 11 '21 at 17:25