Passing data from operation to fragment using Otto
In my application, I am adding Fragments dynamically to the container in the main view of the activity. I would like to know what is the best way to transfer data when using Otto when adding a fragment. Currently this is how I do it please in the example I am not submitting my CustomObject
Inside my main activity
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, MY_CUSTOM_FRAGMENT).commit();
BusProvider.getInstance().post(produceCustomString());
Inside my fragment
@Subscribe
public void onCustomStringChanged(String customString) {
}
source to share
Methods annotated with @Subscribe
will automatically be called if you also have a method @Produce
for the same registered type.
The best way to inform new pieces of data like this is the method @Produce
for activity:
@Produce public String produceCustomString() {
return "Hello, World!";
}
And then all your fragments that have methods @Subscribe
:
@Subscribe public void onCustomStringEvent(String event) {
// ...
}
When you register a fragment that has this method, Otto will call the method @Produce
on the action to get the last value it will pass to the fragment method.
source to share