Pass data to the previous Fragment

Luyen Ninh
Culi Tech Viet
Published in
2 min readMar 7, 2020

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.

Photo by Farzad Nazifi on Unsplash

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 :

Pop back result Ok

Or pop back with the result Cancel:

Pop Back cancel the result

So now, we can receive data from call back result by the way override function onActivityResult on fragment:

onActivity result 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:

Make extension function for Fragment

And using this function with a little code like:

using with callback result for each request

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.

--

--