---
# System prepended metadata

title: EventBus Dependency
tags: [Android Dependency]

---

# EventBus Dependency
###### tags: `Android Dependency`

[TOC]

# What it is for?
It helps to publish/subscribe event for Android and Java.

# Dependency
```java=
//Event Bus
def event_bus_version = '3.1.1'
implementation "org.greenrobot:eventbus:${event_bus_version}"
```

# How to use it?

## Github Provided Steps
![](https://i.imgur.com/q9GKhGc.png)


## Example

### 1. Define enum to set all possible event states

```java=
public enum EventBusEnum {
    //Here We can state all states that might be used in Event Bus
    LOGIN_SUCCESS,
    LOGIN_FAIL,
    LOGOUT
}
```

### 2. Define EventBusMsg class
Here we can use previous file as type for this class. By using **T**, we can store the data/msg we are handling at the momment and send it to our msg receiver.
```java=
public class EventBusMessage<T> {
    private EventBusEnum eventBusType;
    private T message;

    public EventBusEnum getEventBusType() {
        return eventBusType;
    }

    public void setEventBusType(EventBusEnum eventBusType) {
        this.eventBusType = eventBusType;
    }

    public T getMessage() {
        return message;
    }

    public void setMessage(T message) {
        this.message = message;
    }

}
```

### 3. Subscribe/unregister to EventBus in Activity/Fragment

We have to set up registration and unregistration of event bus.
>**Note:** Avoid double registration, so use **EventBus.getDefault().isRegistered(this)** to check if it was registered before.[color=red]

**Activity:**
```java=
@Override
protected void onStart() {
    super.onStart();
    EventBus.getDefault().register(this);
}

@Override
public void onStop() {
    super.onStop();
    EventBus.getDefault().unregister(this);
}

```

**Fragment:**
It can also be done in onStart/onCreateView or another primary methods and unregister in onDestroyView/onDestroy.
```java=
@Override
public void onStart() {
    super.onStart();
    if (!EventBus.getDefault().isRegistered(this)){
        EventBus.getDefault().register(this);
    }
}

@Override
public void onDestroy() {
    if (EventBus.getDefault().isRegistered(this)){
        EventBus.getDefault().unregister(this);
    }
    super.onDestroy();
}
```

### 4. Define Receiver part
By checking the EventBusType, we can know which action we have to refer. But be aware of null before checking.
```java=
@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(EventBusMsg<Object> event){
    EventBusEnum type = event.getEventBusType();
    if(type == null){
        return;
    }

    switch (type){
        case LOGIN_SUCCESS:
            Log.d("EVENT_BUS", "LOGIN_SUCCESS");
            break;
        case LOGOUT:
            Log.d("EVENT_BUS", "LOGOUT");
            break;
        case LOGIN_FAIL:
            Log.d("EVENT_BUS", "LOGIN_FAIL");
            try{
                ErrorMsg errMSg = (ErrorMsg) event.getMessage();
                Log.d("EVENT_BUS", errMSg.getErrMsg());

            } catch (Exception e){
               e.printStackTrace();
            }
            break;
        default:
            Log.d("EVENT_BUS", "DEFAULT");
    }
}
```

### 5.Let's post an Event Bus
```java=
private void initView(){
    findViewById(R.id.btn_login_success).setOnClickListener(v -> {
        EventBusMsg<String> event = new EventBusMsg<>();
        event.setEventBusType(EventBusEnum.LOGIN_SUCCESS);
        event.setMessage("Welcome!");
        EventBus.getDefault().post(event);

    });
    findViewById(R.id.btn_login_fail).setOnClickListener(v -> {
        ErrorMsg errorMsg = newErrMsg(400, "Not Found");
        EventBusMsg<ErrorMsg> event = new EventBusMsg<>();
        event.setEventBusType(EventBusEnum.LOGIN_FAIL);
        event.setMessage(errorMsg);
        EventBus.getDefault().post(event);

    });
    findViewById(R.id.btn_logout).setOnClickListener(v -> {
        EventBusMsg<String> event = new EventBusMsg<>();
        event.setEventBusType(EventBusEnum.LOGIN_SUCCESS);
        EventBus.getDefault().post(event);
    });
}


private ErrorMsg newErrMsg(int code, String errMsg){
    ErrorMsg errorMsg = new ErrorMsg();
    errorMsg.setErrCode(code);
    errorMsg.setErrMsg(errMsg);
    return errorMsg;
}

```


# Delivery Threads (ThreadMode)
ThreadMode: POSTING
ThreadMode: MAIN
ThreadMode: MAIN_ORDERED
ThreadMode: BACKGROUND
ThreadMode: ASYNC