Communicating between Activities and Fragments when using Navigation Architecture Component - android

I want to let the host Activity know when something happens in a Fragment. Traditionally, I would have an interface with a callback that the Fragment can call, but now we are ofc using the navigation architecture component.
Is there a way to pass a reference to the host activity down to the fragments or how would I otherwise solve the "Communication between activities and fragments" situation?
Thanks!

You can use the LiveData data holder class for such purposes.
Here is an article explaining both Fragment <--> Fragment communication and Activity <--> Fragment communication.

you can have a shared ViewModel between your activity and all of your fragments. and use liveData in that viewModel. so when something happens in the fragments you change the liveData and you observe the liveData in the activity

You can use a Shared ViewModel (https://developer.android.com/topic/libraries/architecture/viewmodel#sharing)
It would be alive while the activity is and all child fragments can access it.
A LiveData in a Shared ViewModel, for example, could be listened to in all the fragments. If one of those fragments change the data all others would get that change.

Related

What should be lifeCycleOwner of LiveData-Fragment or Activity?

Will Activity be lifeCycleowner of LiveData?
or
Will Fragment be lifeCycleowner of LiveData?
The answer is as per my understanding and I would say, it depends on where LiveData is being used or called from?
Let's go through some basics.
LifecycleOwner by definition means
A class that has an Android lifecycle. These events can be used by custom components to handle lifecycle changes without implementing any code inside the Activity or the Fragment.
Lifecycle
Lifecycle-aware components perform actions in response to a change in the lifecycle status of another component, such as activities and fragments. These components help you produce better-organized, and often lighter-weight code, that is easier to maintain.
Since the Lifecycle of Activity and Fragments are different.
Activity - Activity has its own lifecycle
Fragment - Each Fragment instance has its own lifecycle. To manage the lifecycle, Fragment implements LifecycleOwner.
Fragments are basically contained inside an Activity; so if the Activity is destroyed, Fragments will also be destroyed.
But it's not necessary that if fragments are destroyed, Activity will also be destroyed.
Live Data
You can register an observer paired with an object that implements the LifecycleOwner interface. This relationship allows the observer to be removed when the state of the corresponding Lifecycle object changes to DESTROYED.
Now coming back to your question.
when LiveData is observed in Activity, the lifecycle owner is Activity itself.
when LiveData is observed in Fragment, the lifecycle owner is Fragment itself.
What should be lifeCycleOwner of LiveData-Fragment or Activity?
It really depends on where you're using liveData. LiveData is lifecycle-aware, which means they respect the lifecycle of android app components.
If you are using liveData to observe data inside activity, then you should observe using activity.
If you are using liveData to observe data inside a fragment, then there is no point in using activity as lifecycleOwner. Using activity would lead to a memory leak, if fragment is replaced or removed, as liveData would still hold a strong reference to the fragment, which will be kept until activity is destroyed.
We should use viewLifecycleOwner inside fragments, as they are bind to the lifecycle of fragments.
As stated in the Google documentation
Each Fragment instance has its own lifecycle. When a user navigates and interacts with your app, your fragments transition through various states in their lifecycle as they are added, removed, and enter or exit the screen.
So each fragment and activity have their own lifecycle.
When you observer LiveData in the fragment or activity you pass the lifecycleowner associated with that fragment or activity.

How do I store a data from a fragment so it can be reuse in a MVVM architecture?

I have know that an Activity/Fragment has to create a ViewModel, and the ViewModel can be created from a ViewModelFactory. And the ViewModel itself are using a data repository which handles the data from either database or network. And the ViewModel is not a singleton.
For example, I have an activity which has two fragment, fragment A and fragment B, and I'm only able to access them one by one. In the fragment A, I load some data from a repository which came from a network or database. When I navigate to fragment B, the data in a fragment A is lost, so I have to load it back from a network or database which takes time. Because of that I would like to store my data somewhere in the runtime.
My question, what is the best approach to solve this problem? Is it okay to create a singleton in the repository?
you need to use a shared viewModel, a ViewModel that is shared between your fragments and survives navigating between certain fragments.
Implementation depends on what you use in your project. you can create a ViewModel in the activity and access them from your fragments and put the shared data in this ViewModel. or if you are using navigation component you can have a shared ViewModel per nav graph. and with dagger and koin you can define a costume scope for your ViewModel to survive. see these links:
Share data between fragments
Share data between fragments with shared viewModel

Is it possible to call ViewModel methods from fragments through an Activity or is it a bad practice?

I have an Activity and 4 fragments in it. At first I wanted to do for each fragment of the ViewModel. But the situation is such that I also need ViewModel for Activity. I want to know if it would be an error to make the ViewModel just for the Activity and call the necessary methods from the fragments using getActivity? For example, call getActivity().myViewModel.callMethod() at fragment? Wouldn't this approach be wrong?
Yes, you can use the ViewModel of the Activity at a fragment, but not like that getActivity().myViewModel.callMethod(). It should be like this
YourViewModel viewModel = ViewModelProviders.of(getActivity()).get(YourViewModel.class);
And it's a good practice to share data between fragments.
Official doc of Google says
That way, when the fragments each get the ViewModelProvider, they
receive the same SharedViewModel instance, which is scoped to this
activity.
This approach offers the following benefits:
The activity does not need to do anything, or know anything about this
communication.
Fragments don't need to know about each other besides
the SharedViewModel contract. If one of the fragments disappears, the
other one keeps working as usual.
Each fragment has its own lifecycle,
and is not affected by the lifecycle of the other one. If one fragment
replaces the other one, the UI continues to work without any problems.

Creating my own ViewModelStore to control ViewModel lifecycle

It is stated in google example that to communicate from fragment to fragment, you could use the ViewModel scoped to the Activity. The problem with this approach is that, then the ViewModel will last until the Activity is destroyed.
In a Single Activity Application, this means that the activity will be littered with ViewModels which might not be needed anymore. You will also have problem with states if these ViewModels won't be cleared properly.
So I look around at how to alter the lifecycle of the ViewModel so that I doesn't have to be tied to the Activity lifecycle but be longer than the lifecycle of a Fragment. This will then be very useful for Multi-step / Transactional flow of screens where the requirements are filled-up during the screen flow process.
So basically, I would want a ViewModel to be scoped less than the activity but longer than a fragment.
To accomplish this, I created my own ViewModelStore and persist it across configuration the same way FragmentActivity persist its own ViewModelStore. Then when initializing the view model I will use,
ViewModelProvider(myCustomViewModelStore, myFactory).get(SomeViewModelClass::class.java)
Since the ViewModel is not scoped to my custom ViewModelStore, I could easily call viewModelStore.clear() to control the lifecycle of the ViewModel.
I was wondering whether this is a good idea and whether someone out there is using the same idea.
Thanks in advance!
As of Navigation Component 2.1.0-aplha02, ViewModels can now be scoped to transaction flows through the Navigation Component navigation graph.

Sharing data between fragment and its parent activity using ViewModel

I would like to ask if it's correct to share the same ViewModel between Fragment and its Activity.I have UserDetailActivity and UserDetailFragment. Can I use the same ViewModel to display detail data of a user in the UserDetailActivity and UserDetailFragment or is there better approach.
Yes you can pass ViewModal object from a Activity to Fragment or vice-versa by implementing Parcelable into ViewModal class and can share object with fragment setArguments() method.
I am not using MVVM but I think its the same with MVP, I use the same Presenter(ViewModel in your case) with my Activity and its child Fragment. It make since because a Fragment is literally a fragment of an Activity. There might be some special cases where you really want to separate viewModel of Fragment and Activity, but most of the time, they share. About the initialization, dont pass your viewmodel directly, you can use dagger and inject it.

Categories

Resources