0

I am using Android navigation component, and I have a fragment, FragA, that is being reused in multiple navigation graph, I want to have different instances of ViewModel for this fragA in each graph. I looked around and found by navGraphViewModels(R.id.child_graph) however this requires to know which graph I am coming from, but I don't know it since FragA is being reused.

I can't pass graph in arguments/bundle since doing something like private val childGraphScopedViewModel: ChildGraphScopedViewModel by navGraphViewModels(arguments.getInt) { won't work, because arguments is still Null when that line of code is being called.

So my question is how can make the graph id dynamic? Do I have to write my custom implementation that mirrors by navGraphViewModels? (Also I may need such a thing to work in java/kotlin)

M.Baraka
  • 725
  • 1
  • 10
  • 24
  • do you want `different instances of ViewModel` of the same class or different classes? – denvercoder9 Nov 01 '20 at 18:42
  • @denvercoder9 different instance of same ViewModelA for a same FragA that is opened in 2 different Navigation Graph – M.Baraka Nov 02 '20 at 00:07
  • 1
    use `by viewModels()` instead of `by navGraphViewModels(..)`. Please read this answer and the comments as well https://stackoverflow.com/a/61974340/2235972 That might explain some stuff. Also, read the docs on `viewModels()` and `navGraphViewModels()` – denvercoder9 Nov 02 '20 at 22:17

1 Answers1

1

I can recommend you to use SubFrag1, SubFrag2 ... of FragA for each graph.

open class FragA

class SubFrag1: FragA()

class SubFrag2: FragA()