androidandroid-activityevent-busotto

Otto event bus not fired from an activity to another activity with fragments


I am not new to using event bus but I got strange behavior in the following scenario:

I have MainActivity which have two fragments that need to update their contents using Otto event bus from SecondActivity which launched from MainActivity. The problem is, when SecondActivity launched, MainActivity paused and thus, the bus will be unregistered inside its onPause method and when EventBus fired its event from SecondActivity, it won't be received by the two fragments under MainActivity.

Btw, MainActivity has a subscriber method to received an update from an AsyncTask thread and as a result it should register and unregister event bus as well.

Here is my BusProvider class code:

public class BusProvider {

   private static final Bus BUS = new Bus(ThreadEnforcer.ANY);

   public static Bus getInstance() {
       return BUS;
   }

   private BusProvider() {
   }
}

Here is my event bus code for MainActivity:

@Override
protected void onResume() {
    super.onResume();
    bus.register(this);
}

@Override
protected void onPause() {
    super.onPause();
    bus.unregister(this);
}

@Subscribe
public void onAsyncResult(SomeEvent event) {
    // do something
}

Here is my FragmentA and FragmentB event bus code:

@Override
protected void onResume() {
    super.onResume();
    bus.register(this);
}

@Override
protected void onPause() {
    super.onPause();
    bus.unregister(this);
}

@Subscribe
public void onValueUpdate(UpdateEvent event) {
    mTvValue.setText(event.value);
}

Now this code inside SecondActivity which I need to update both fragments from it:

BusProvider.getInstance().post(new UpdateEvent("Value Updated!"));

Whats happening is that the UpdateEvent fires from SecondActivity but not received by the two fragments A and B.

Any helpful answer is appreciated.


Solution

  • As you correctly pointed out:

    The problem is, when SecondActivity launched, MainActivity paused and thus, the bus will be unregistered inside its onPause method

    Your fragments' onPause methods are being executed once SecondActivity is launched, causing them to unregister from event bus. So, you need to move register and unregister to onCreate and onDestroy respectively

    FragmentA and FragmentB event bus code should be:

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        bus.register(this);
    }
    
    @Override
    public void onDestroy() {
        super.onDestroy();
        bus.unregister(this);
    }