Junior — Middle
Can you explain the principle of operation of the Fragment Result API and its purpose in Android application architecture?
sobes.tech AI
Answer from AI
Fragment Result API in Android is designed for exchanging data between fragments without directly linking them.
How it works:
- One fragment sets a listener for a specific result key.
- Another fragment sends a result with that key.
- The system passes data to the listener, which processes it.
This simplifies communication between fragments, especially when they are not in a direct hierarchy or when avoiding tight coupling.
Example usage:
// In the receiving fragment
setFragmentResultListener("requestKey") { key, bundle ->
val result = bundle.getString("bundleKey")
// process result
}
// In the sending fragment
val result = Bundle().apply { putString("bundleKey", "data") }
setFragmentResult("requestKey", result)
Thus, Fragment Result API promotes cleaner architecture and easier management of navigation and data exchange between fragments.