More of a better practice question, I have a fragm...
# android
a
More of a better practice question, I have a fragment with a viewpager inside which items are also fragments. Depending on the even in a child fragment inside a viewpager I need to notify the parent fragment (the one that contains viewpager). I see a couple of ways like passing a function to the fragment constructor , using an interface and casting the context to it inside the child fragment. What other (possibly better ways) do you all see for this use case?
f
Use a
ViewModel
in an activity scope.
a
It is a single activity pattern , so my viewmodel with activity scope will be responsible for the logic in one of 15 fragments that are present in the app, do you think it is ok?
I was going to use viewmodel scope with navigation through to fix that but I can't up my navigation version in the project now
f
Let's say
ViewPagerViewModel
that holds only what matters for those pager fragments. They can be notified through
Activity
.
a
Ok, how would they be notified through activity, having an interface that activity implements and casting it to the context in each fragment?
Or is there another way?
a
So they will get instances of that view model that has one instance of livedata, that view model will be a Singleton and they will write events to it ?
f
You access the same
ViewModel
(activity scoped) in each pager fragment and in their parent activity. Any change / action on pager fragment can trigger
LiveData
in viewmodel.
a
To access the same view model you have to get the same instance of the same viewmodel in each fragment aka singleton
It imposes a problem that viewmodel will not be cleared when those fragments are destroyed as its scope is bigger and the second part of the problem when you go to that page again it will have the old data (as viewmodel will outlive the fragments) so you have to clear it manually
f
You do not have to refresh manually if you observe same
LiveData
.