Comminucating From Fragment to Activity Easy Way

Fragment Result API vs SharedViewModel vs setTargetFragment()/onActivityResult() vs Interfaces

Architectural structure of an Android single-activity screen

The development of modern native Android apps today tends to be based on single-activity architectures.

This means that a single activity as a parent can have one or more fragments as children. Only the fragments are replaced within an event or navigation, so that the original parent activity continues to function as a container. It should be noted that viewed hierarchically, a child fragment can itself have child fragments.

Possible solutions for runtime communication between the fragments

This architectural approach creates new challenges, such as communication among the fragments at runtime. If you have the option of transferring information parameters when you call a new fragment, you have several options when communicating below the fragments and, if applicable, the parent activity:

• Interfaces
• SharedViewModel
setTargetFragment()/onActivityResult()

Using interfaces for communication between fragments and activities is a conceivable but also an outdated approach that involves a certain amount of overhead and is currently not directly recommended by Google in this form.

At first glance, a SharedViewModel seems to represent a one-size-fits-all solution, which is also recommended by Google for communication between the fragments.

Here, the parent activity and the fragments share a common ViewModel and any start fragment could fire corresponding events via the observer pattern using LiveData or Flows, to which a reaction can then be made in the respective target fragment.

This is a viable approach for most situations, but it has limitations with a fragment that is often reusable, such as a fragment with a search mask displaying the search results. As soon as different interaction fragments have even minimal individual communication requirements with the search fragment, this can very quickly lead to a complex, error-prone and confusing overhead.

The communication at runtime between the fragments with an intent via the target fragment APIs (setTargetFragment/onActivityResult) in connection with a request and a result code has been deprecated since API level 28 and with the fragment-ktx library from version 1.3.0-alpha04. Instead, the new Fragment Result APIs are recommended for communication between the fragments.

Fragment Result API

Google describes the use of the Jetpack fragment library with consistent behavior across devices and access to the lifecycle.

Since version Fragment-ktx:1.3.0-alpha04 (04/29/2020) FragmentManagers can be used for communication among Fragments
Version 1.3.0 has been released as stable since February 10th, 2021.
The most recent version can be viewed here:
https://developer.android.com/jetpack/androidx/releases/fragment

The FragmentManager now implements the FragmentResultOwner by default and overwrites the methods for setting and cleaning up Fragment Results as well as the Fragment Result Listener.

How it works can be described as follows:

  • The FragmentManager keeps the Fragment Results and the Fragment Result Listener in different maps with a requestKey as a unique ID,
    • The fragment result listener registered with a corresponding requestKey is notified as soon as the results are set or updated,
    • A "resultCode" as when using onActivityResult is no longer required, and data is also sent and received via a bundle. All data types that a bundle supports can be used here,
    • In this way, fragments can communicate in the same FragmentManager and from child to parent fragments or vice versa.

Communication via the same FragmentManager

Communication between two fragments on the same FragmentManager occurs whenever the fragments communicate at the same hierarchy level and can be illustrated as follows:

The sender FragmentA sends a friend's name to the FragmentManager via the setFragmentResult() command. The message is wrapped using a request key and the friend's name using a bundle key.

As soon as it has reached the "STARTED" state, the receiver fragment FragmentB receives the result by calling setFragmentResultListener() and executes the listener callback for the request key, via which a message was previously sent by the sender.
The values of the message are obtained via the corresponding bundle keys.
In this example, a value was passed and immediately received, and then mapped to a LiveData attribute in the target fragment's ViewModel. Both sender and receiver access the same FragmentManager.

Communication between parent and child fragments

As already mentioned in the introduction, viewed hierarchically, fragments can themselves host fragments. In this case, the parent fragment needs the childFragmentManager to receive data from the child fragment, or to send data to the child fragment itself.

As in the previous example, the target fragment receives the data once it has reached the STARTED state.

The child fragment sets or retrieves its message via its fragment manager.

Preserve data in the parent activity

If the parent activity wants to receive messages from a fragment, the supportFragmentManager is required in this case.

What to consider

In order to ensure a smooth process with the Fragment Result API, the following principles of the API must be taken into account:

  • Only one listener can be registered for a specific request key.
    o If more than one listener is registered on the same key, the previous one will be replaced by the newest listener.
  • If setFragmentResult() is fired multiple times from the sender fragment, the target fragment always gets the most recent value.
  • If a value is sent via setFragmentResult() and no listener is registered for the key, the most recent value is stored in the FragmentManager until a listener with the same key is registered. This behavior corresponds to a "hot observable".
    o As soon as the listener is registered and the fragment lifecycle has reached the "Lifecycle.State.STARTED" state, the value is consumed immediately afterwards.
  • The value is discarded by the FragmentManager once the target fragment has consumed it.

Recap

With the new Fragment Result API, communication of simple and small data packets between fragments at runtime is even easier and superfluous overhead has also been removed.
With consideration of the life cycle and the rules/principles for the consumer behavior of the messages, such as uniqueness and timeliness of a message, a certain stability is also guaranteed, so that the Fragment Result API is a very good alternative or at least an addition to a SharedViewModel for runtime communication with each other.
In addition, it very efficiently solves the problem between fragments that are reused multiple times and that require different exchanges of data in certain views.

vesselsfroment84.blogspot.com

Source: https://towardsdev.com/state-of-the-art-communication-between-fragments-and-their-activity-daa1fe4e014d

0 Response to "Comminucating From Fragment to Activity Easy Way"

Publicar un comentario

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel