I'm using single activity pattern and in one particular screen, I want to share one viewModel with two different fragments. After researching for a bit, I found these solutions:
- I use the activity instance whilst creating the viewModel, so that both of my fragments get the same instance. but the drawback with this approach would be, that the viewModel instance will be alive till the application is running.
ViewModelProviders.of(Activity.this, viewModelFactory).get(CustomViewModel::class.java)
I can add a Tag to the first fragment while launching it and pass the instance of first fragment while creating viewModel in Second fragment. This way I will have a single instance of ViewModel shared across two fragments.
ViewModelProviders.of(fragmentManager?.findFragmentByTag(TAG)!!, viewModelFactory).get(CustomViewModel::class.java)
I read one more method somewhere to share viewModel, but I forgot because it didnt work for me.
I would like to know which method would be the best for sharing viewModel across fragments. What are my options here? Thanks.