Pass data to the previous Fragment
When we using fragment widely in the application to show data. Sure We have faced a question: “What is best practice to passing data to the previous fragment without EventBus, interface callback ?”. In the article, I will be showing a way to resolve that question.
Using onActivityResult
When we start a fragment, I used a set target fragment and add fragment with a request code similar the way we start an activity for the result:
And pop back to the previous fragment with the result OK :
Or pop back with the result Cancel:
So now, we can receive data from call back result by the way override function onActivityResult on fragment:
Above is a simple way we can resolve the question, but if we used to call back onActivityResult the flow business code can be a break and reduce readable.
With Kotlin, We can modify just a little bit some code to increase readable. On the Base class fragment, we need to add some code below to handle result:
And using this function with a little code like:
And on Fragment A, we need popBack and push data to intent:
Conclusion
Using combine extension function and function receiver we can make a DSL code short than, readable. I think it will be helpful in your project.