3

In my application I'm adding Fragments dynamically to the container in main activity view. I would like to know what is the best way to pass data when using Otto when we add Fragment. Currently this is how I'm doing it, please in example I'm not posting 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) {
    } 
Mayank Mehta
  • 689
  • 1
  • 8
  • 12

1 Answers1

12

Methods annotated with @Subscribe will automatically be called if you also have a @Produce method for the same type registered.

The best way to inform new fragments of data like this is you have an @Produce method on the activity:

@Produce public String produceCustomString() {
  return "Hello, World!";
}

And then all your fragments which have @Subscribe methods:

@Subscribe public void onCustomStringEvent(String event) {
  // ...
}

When you register a fragment which has this method, Otto will call the @Produce method on the activity to get the latest value which it will pass to the fragment's method.

gMale
  • 17,147
  • 17
  • 91
  • 116
Jake Wharton
  • 75,598
  • 23
  • 223
  • 230
  • Thanks Jake, that helped. Actually i had @Produce in my activity but i was still manually calling post after adding the fragment. Will remove that extra post. – Mayank Mehta Jan 30 '13 at 00:12
  • Tried to edit the answer to replace "public void String" with "public String" and the system doesn't allow me to do so saying "Edits must be at least 6 characters" :-) – mingfai Jun 10 '13 at 14:50