M.Baraka
M.Baraka

Reputation: 755

Android: Different ViewModel instance for different Navigation Graph java/kotlin

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)

Upvotes: 1

Views: 282

Answers (1)

Rustam Samandarov
Rustam Samandarov

Reputation: 892

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

open class FragA

class SubFrag1: FragA()

class SubFrag2: FragA()

Upvotes: 2

Related Questions