DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations

What Is the EventBus Library and How Does It Work?

Learn about the EventBus library for Android and how it makes it easier to manage communication between components in your application.

Abhishek Tripathi user avatar by
Abhishek Tripathi
·
Aug. 08, 18 · Tutorial
Like (8)
Save
Tweet
Share
519.82K Views

Join the DZone community and get the full member experience.

Join For Free

EventBus is an open-source Android library that simplifies communication between Activities, Fragments, Threads, and Services, with less code and better quality. When we develop an Android application, we need to manage a lot of intercommunication between Android components, which sometimes becomes very difficult to manage. The EventBus library makes this task easy.

Why EventBus?

The main reason we should use EventBus is loose coupling. Sometimes, you want to process specific events that are interested in multiple parts of your application, like the presentation layer, business layer, and data layer, so EventBus provides an easy solution
for this.

Features of the EventBus Library

  1. Simple, yet powerful.

  2. Battle-tested.

  3. High performance.

  4. Convenient annotation-based API.

  5. Event and subscriber inheritance.

You need to have four things to implement EventBus:


1. An EventBus object.

EventBus myEventBus = EventBus.getDefault();

2. An Event normal POJO class.

public class DataSyncEvent {
    private final String syncStatusMessage;

    public DataSyncEvent(String syncStatusMessage) {
        this.syncStatusMessage = syncStatusMessage;
    }

    public String getSyncStatusMessage() {
        return syncStatusMessage;
    }
}

3. The sender which will send the event.

EventBus.getDefault().post(new DataSyncEvent("Sync SuccessFully”);

4. The subscriber, someone who will listen to our event.

@Subscribe
public void onEvent(DataSyncEvent syncStatusMessage)
{
    Toast.makeText(this, syncStatusMessage.getSyncStatusMessage(), Toast.LENGTH_SHORT).show();
}

The last two steps are to register and unregister the EventBus that wants to listen to the event. The best way is to register it in the onStart method and unregister it in the onStop method of the activity.

@Override
protected void onStart() {
    super.onStart();
    EventBus.getDefault().register(this);
}
@Override
protected void onStop() {
    super.onStop();
    EventBus.getDefault().unregister(this);
}

Let's take a simple example. In our project, if we want to sync our data to the server at the time of the application's launch, for this, simply start an intent service from the launcher activity of your application and, through the intent service, sync the data to the server. After that, notify the screen (through theEventBus library) which is currently visible to the user about syncing.

Implementation of EventBus

Add the dependencies in the gradle file.

compile 'de.greenrobot:eventbus:2.4.0'

Add the intent service class, which will start at the time of application launch.

    public class SyncDataService extends IntentService
    {
        public SyncDataService()
        {
            super("SyncDataService");
        }

        @Override
        protected void onHandleIntent(Intent intent)
        {
            //first check if internet is availabe or not.
            if(DeviceManager.isInternetAvailableOnDevice())
            {
//            try
//            {
//              //write the code to sync the data to Server
                //post the event after sync complete 
                EventBus.getDefault().post(new DataSyncEvent("Data Sync SuccessFully"));
//            }
//            catch (RTITBException exception)
//            {
//                LogManager.getInstance().addLog(exception.getExceptionCode(),exception.getMessage(),exception);
//            }
            }
        }
    }

The main Activity:

public class MainActivity extends AppCompatActivity
{
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    //Register the EventBus
    @Override
    protected void onStart()
    {
        super.onStart();
        EventBus.getDefault().register(this);
    }
    //UnRegister the EventBus
    @Override
    protected void onStop()
    {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }
    //The Method which will call every time when data sync to server
    @Subscribe
    public void onEvent(DataSyncEvent syncStatusMessage)
    {
        //you can do whatever you want releted with UI
        Toast.makeText(this, syncStatusMessage.getMessage(), Toast.LENGTH_SHORT).show(); 
    }
}

If any other component of your application wants to listen to the event, we only need to register for the EventBus as mentioned in the above method onStart and override the method onEvent.

The EventBus library is just like a radio frequencyl; if you wish to listen to any song, you simply need to set the frequency to that station. Likewise, the EventBus library posts events; if any component wants to listen to that event, then we need to register that component for the EventBus object and we will get that event in the onEvent method.

Library

Published at DZone with permission of Abhishek Tripathi. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Little's Law and Lots of Kubernetes
  • How To Use Linux Containers
  • DevOps for Developers — Introduction and Version Control
  • FIFO vs. LIFO: Which Queueing Strategy Is Better for Availability and Latency?

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: