5

I seem to be having one of two issues here. Either an error like:

java.lang.IllegalStateException: Event bus [Bus "default"] accessed from non-main thread Looper

Or, if I've managed to "address" that, I simply never receive the event in my subscriber.

Currently, I have a class, cobbled from a few sources, sub-classing Bus:

public class MainThreadBus extends Bus {
    private static Bus _bus;
    private Handler _handler = new Handler(Looper.getMainLooper());

    public MainThreadBus() {
        if (_bus == null) {
            _bus = new Bus();
        }
    }

    @Override public void register(Object obj) {
        _bus.register(obj);
    }

    @Override public void unregister(Object obj) {
        _bus.unregister(obj);
    }

    @Override public void post(final Object event) {
        if (Looper.myLooper() == Looper.getMainLooper()) {
            _bus.post(event);
        } else {
            _handler.post(new Runnable() {
                @Override public void run() {
                    _bus.post(event);
                }
            });
        }
    }
}

Which is used in an Activity like this:

@Subscribe
public void requestProgressAvailable(RESTRequestProgress progress) {
    processProgress(progress);
}

@Override
protected void onResume() {
    super.onResume();

    _bus = new MainThreadBus();
    _bus.register(this);
}

@Override
protected void onPause() {
    super.onPause();

    _bus = new MainThreadBus();
    _bus.unregister(this);
}

And publishing from an IntentService like this:

_bus = new MainThreadBus();
_bus.post(request.createRESTRequestProgress(RESTRequest.STATUS_STARTED));

And the messages are not received. An alternate configuration had me receiving the thread error, so I'm going with this, for now.

So, what am I missing, or doing wrong?

EDIT: Thanks to Andy below for pointing out that my code wasn't acting as I thought it was. The code above now reflects modifications based on that feedback.

Michael
  • 4,010
  • 4
  • 28
  • 49
  • I have re-implemented using greenrobot EventBus and it's working, though I'm still interested in the Otto solution. – Michael Jul 04 '13 at 06:38

2 Answers2

8

Aside from the fact this implementation isn't a Singleton, when getting this error, you can use the threadEnforcer.ANY option in the constructor:

private static final Bus BUS = new Bus(ThreadEnforcer.ANY);
Niels
  • 9,264
  • 4
  • 29
  • 26
3

The problem is that your code is not interacting with the same bus instance. Instead of creating a new MainThreadBus in each case, you should access the same bus, for example a singleton obtained from a factory or via injection.

Andy Dennie
  • 6,012
  • 2
  • 32
  • 51
  • I had thought my code above was using a static _bus and only setting it once but, clearly, it wasn't. I've modified the code above to reflect a new approach, which still isn't working. – Michael Jul 04 '13 at 00:24