Issue Subscribing to/Receiving Otto Event Posted from IntentService
Asked Answered
V

2

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.

Vitta answered 3/7, 2013 at 4:39 Comment(1)
I have re-implemented using greenrobot EventBus and it's working, though I'm still interested in the Otto solution.Vitta
P
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);
Paresis answered 9/4, 2015 at 13:35 Comment(0)
S
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.

Stonge answered 3/7, 2013 at 23:27 Comment(1)
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.Vitta

© 2022 - 2024 — McMap. All rights reserved.