Issue Subscribing to/Receiving Otto Event Posted from IntentService

Michael picture Michael · Jul 3, 2013 · Viewed 7.1k times · Source

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.

Answer

Niels picture Niels · Apr 9, 2015

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);