EventBus is an Android optimized event bus that simplifies communication between Activities, Fragments, Threads, Services, etc. Less code, better quality. You see, if you have developed android applications before, you will agree with me when I say that communication between different parts of the project code can be a pain. Using interfaces might work but not all the times. The idea though would be to stick to the best design patterns in Java which include decoupling your code. Eliminate dependencies. Let us get started!
First Things First
To use EventBus, you should add the following to your build.gradle file (app-level file)
1 2 3 4 5 6 7 8 |
dependencies{ ..... compile 'org.greenrobot:eventbus:3.0.0' } |
Sync your project! Now, moving on ….
Next, create a simple Java class that will represent your event.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
public class LoginAuthorizationEvent{ private boolean isLoginSuccessful; private String responseMessage; public LoginAuthorizationEvent(boolean success, String message){ this.isLoginSuccessful = success; this.responseMessage = message; } public boolean isLoginSuccessful(){ return isLoginSuccessful; } public String getResponseMessage(){ return responseMessage; } /* You can add setters here if you want */ } |
Now is the time to use EventBus. It is easier than you might actually think.
Use Case
In this typical scenario, a user attempts a LOGIN by making an HTTP request to a remote server somewhere in the North Pole or your basement! We both know that in such a network operation, a user will have to wait for the request to complete – this could take a few seconds depending on the speed of the internet connection.
What you might want to do is listen for login success or login failure and then respond accordingly to redirect the user to the respective part of the application. Now let us do this.
LoginActivity.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
public class LoginActivity extends AppCompatActivity{ @Override protected void onCreate(Bundle saveInstanceState){ super.onCreate(saveInstanceState); setContentView(R.layout.login_activity_layout); //register EventBus (this activity is a subscriber) EventBus.getDefault().register(this); } @Override public void onDestroy(){ super.onDestroy(); //unregister eventbus here EventBUs.getDefault().unregister(this); } } |
Before we come back to handle notifications from our publisher inside our activity, let us write up our class that acts as our PUBLISHER.
LoginUserAsync.java
I know, don’t call me names for using an AsyncTask for this example. Let us talk about why they are not good for your health later on! This is for demonstration purposes ONLY.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
public class LoginUserAsync extends AsyncTask<String, Void, String>{ @Override protected String doInBackground(String params ...){ //get credentials from params arguments String userName = params[0]; String password = params[1]; String url = params[2]; // this is upto you now! //Now do the actual HTTP request (POST) return jsonResponse; } @Override public void onPostExecute(String result){ // convert your String result to JSON Objects then get response code // then check if login was successful or failed //now let us post our Event to our subscribers if(responseCode == 200){ EventBus.getDefault().post(new LoginAuthorizationEvent(true, "Welcome to Uber for Toothpaste")); }else{ EventBus.getDefault().post(new LoginAuthorizationEvent(false, "Login failed! Please check credentials.")); } } } |
Pretty much done here …
Finally, we need to handle the events we just posted above from within our subscribing activity: LoginActivity.java
To do that, we have to add a single method whose parameter is our Event class – the one we created earlier!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
//inside our LoginActivity, simply do @Subscribe public void onEvent(LoginAuthorizationEvent event){ //check if login was successful if (event.isLoginSuccessful()){ startActivity(new Intent(this, OrderToothpasteActivity.class)); }else{ showErrorSnackBar(event.getResponseMessage()); } } |
Ladies and gentlemen, that is how you can easily communicate between different parts of your application without having to write a lot of code or re-inventing the wheel with your own Subscriber or Publisher code!
Like I said earlier, it decouples your code (aka loose coupling).
Although this approach of using EventBus might sound like a work of beauty, it won’t be long before you realize that too many events will result in everyone posting events in your application – this will be recipe for disaster since you might not know who is talking to who and when!
So, use it but not in excess 🙂
I hope you found this post helpful to you and if that is true, please share it with your friends online and consider subscribing for future posts!
Thanks and happy coding my friends!
Nagendra Hari Karthick
can you tell me why we shouldn’t use asynctask with eventbus? tell me why they are not good for health?
sathish kumar
how to send and receive string data between the fragment using Event bus.