j2emanue
j2emanue

Reputation: 62519

Greenrobot eventBus for Android - how to create a non-default event bus

i am making a mvp app and i want it to have the following architecture (more or less) in terms of event bus @greenrobot: enter image description here

The problem is i am using greenrobot as the event bus and i desire to have TWO event buses. one for the data bus and one for the UI bus. These two buses should not know about each other. So to create the first eventBus i do the following:

EventBus myEventBus = EventBus.getDefault();

But i want to create another event bus that is not default so that i can have two. how is this done. I assume i can use eventBusBuilder and do the following:

EventBus.builder().build(); 

and this will create me another eventBus which will not contain events of the default. is this correct ? i cant find any examples online and i wanted to make sure im not missing any configurations. I want it to behave the same as the default bus but just another instance of it.

Upvotes: 0

Views: 690

Answers (1)

Björn Kechel
Björn Kechel

Reputation: 8463

Why do not need seperate EventBus Objects? If you simply Post Events that the other part does not know about, then they cannot liston to the events from each other.

For example you use a custom class called

ModelToDomainEvent 

to send from the model

and a custom class called

DomainToViewEvent

to send from the domain to the presenter view.

You could put these events in sepearate packages to distinguish them even further.

The EventBus itself only organises the events, it is your responsibility to post and listen to the correct events.

But if you really need another instance, you can simply create one using:

EventBus sepearateInstance = new EventBus();

But you need to make sure that the same instance will be used whenever you need it. So best to store it in some static variable, maybe even write your own singleton method for it:

static volatile EventBus alternativeEventBusInstance;
public static EventBus getAlternativeEventBus() {
    if (alternativeEventBusInstance == null) {
        synchronized (EventBus.class) {
            if (alternativeEventBusInstance == null) {
                alternativeEventBusInstance = new EventBus();
            }
        }
    }
    return alternativeEventBusInstance;
}

Upvotes: 2

Related Questions