Subscription to receive and receive Otto Sent from IntentService

I seem to have one of two issues. Any error, for example:

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

Or, if I managed to β€œaddress” this, I simply never receive the event from my subscriber.

I currently have a class paved from several sources, a subclass of Class:

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

Used as follows:

 @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 posting from the IntentService like this:

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

And messages are not accepted. An alternate configuration made me get a stream error, so I'm going with this for now.

So what am I missing or is something wrong?

EDIT: Thanks to Andy below for pointing out that my code is not working as I thought. The above code now reflects changes based on this feedback.

+4
source share
2 answers

Besides the fact that this implementation is not Singleton, when receiving this error you can use the threadEnforcer.ANY option in the constructor:

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

The problem is that your code does not interact with the same bus instance. Instead of creating a new MainThreadBus, in each case you need to access the same bus, for example, a singlet received from the factory or through injection.

+3
source

Source: https://habr.com/ru/post/1489398/


All Articles