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
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • 6 Techniques To Reduce LLM API Costs With the Python Library
  • Runtime Formula Evaluation With MVEL Library in Spring Boot
  • C/C++ Is Where Vulnerability Programs Go to Guess
  • Building a Java 17-Compatible TLD Generator for Legacy JSP Tag Libraries

Trending

  • Idempotency Under Concurrency: Why Your Application Check Isn't the Last Line of Defense
  • RAG Architecture Patterns: Proxy, Caching, and Routing
  • Apache Phoenix: Global Secondary Indexes With Tunable Consistency
  • OwlVigil Open-Sources Its Go SDK for Enterprise AI

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

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.

By 
Abhishek Tripathi
·
Aug. 08, 18 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
521.3K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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.

Related

  • 6 Techniques To Reduce LLM API Costs With the Python Library
  • Runtime Formula Evaluation With MVEL Library in Spring Boot
  • C/C++ Is Where Vulnerability Programs Go to Guess
  • Building a Java 17-Compatible TLD Generator for Legacy JSP Tag Libraries

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook