Raza
Raza

Reputation: 1222

Otto communicating from Fragment to Activity

I've been playing with Otto for the last few days and it's just amazing. However, I've run into a problem, I"m trying to communicate from a Fragment to the Activity. To keep things simple, I have one Activity which hold the Fragment, and in the Fragment I have a Button which just simply posts an event.

@Inject Bus bus;
...
...
bus.post(new ReadStatusEvent("23"));

In the Activity I have a Subscribe method.

@Subscribe
public void onReadStatusEvent(ReadStatusEvent event){
    Timber.i("sub:"+event.getReadStatusID());
}

Here is the event

public class ReadStatusEvent {
  private final String readStatusID;

  public ReadStatusEvent(String readStatusID) { this.readStatusID = readStatusID; }

  public String getReadStatusID() { return readStatusID; }
}

I'm using Dagger, so my Otto Bus is a singleton which is Injected by the SimpleModule file.

@Provides @Singleton
Bus provideBus() {
    return new Bus(ThreadEnforcer.ANY);
}

I've been going at it for the whole day but for some reason the Subscribe method is never called.

Edit: I've just tried using the Otto plugin for Android Studio and whenever I click the @Subscribe or bus.post(..), it keeps searching but doesn't find anything(No usage found so far). I guess I'm doing something terribly wrong somewhere.

Upvotes: 3

Views: 1957

Answers (2)

Sebastian Engel
Sebastian Engel

Reputation: 3695

Your hint concerning the Otto Plugin made me think about your imports.

Are you sure you are using "com.squareup.otto.Subscribe" and not "com.google.common.eventbus.Subscribe" or any other package?

Upvotes: 11

Tadej
Tadej

Reputation: 2921

In order to receive events, a class instance needs to register with the bus. Are you registering the objects holding your subscribers/producers?

bus.register(this); // Example

Upvotes: 0

Related Questions