Search code examples
androidevent-busgreenrobot-eventbusgreenrobot-eventbus-3.0

How to use network communication using greenrobot eventbus?


So , I would like to use the following feature mentioned on GreenRobots website,

EventBus can handle threading for you: events can be posted in threads different from the posting thread. A common use case is dealing with UI changes. In Android, UI changes must be done in the UI (main) thread. On the other hand, networking, or any time consuming task, must not run on the main thread.

What I wish to do is, in my android app i would like to create a event which will handle all my networking tasks(sending and receiving data from the server).

How do i exactly do this?

Should i make a network call in the event POJO and then use OnEvent to do post network call tasks.(I dont think this is correct or is it ?)

Edit : Using an event bus for threading may not be the best option because all your OnEvent call will run synchronously one after the other, which may result in blocking of the bus and also its not meant for that. But the answer below is the way it can be done if at all thats a requirement.


Solution

  • I would suggest using an architecture where an event bus might not be required. An event bus is still useful and I think you can find what you are looking for in their getting started guide.

    Some example code:

    public class EventBusExample extends Activity {
    
      @Override protected void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
        EventBus.getDefault().post(new BackgroundWorkEvent());
      }
    
      @Override protected void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
      }
    
      @Subscribe(threadMode = ThreadMode.ASYNC)
      public void doBackgroundWork(BackgroundWorkEvent event) {
        // do background work here
        // when finished, post to ui thread
        EventBus.getDefault().post(new UiWorkEvent());
      }
    
      @Subscribe(threadMode = ThreadMode.MAIN)
      public void doUiWork(UiWorkEvent event) {
        // on main thread. do ui stuff
      }
    
      public static class BackgroundWorkEvent {
    
      }
    
      public static class UiWorkEvent {
    
      }
    
    }