I have a situation where I use this Library greenrobot/EventBus to save data and pass them on different activities. In this case i use EventBus to pass "order" and "cartItems" OBJECT CustomModel from some activities in a joint activity.
In this activity I have a method that needs values that are distributed in these two objects but these object call in different events like below. I have tried to call this method updateUI() in both events but always one of the objects is NULL.
It is possible to have an event when all objects have been setup?
Any detailed explanation about how events lifecycle works in EventBus is welcomed!
@Subscribe(sticky = true)
public void onOrderEvent(Order order) {
this.order = order;
updateUI();
}
@Subscribe(sticky = true)
public void onBasketProductsEvent(Products products) {
this.basketProducts = products;
updateUI();
}
private void updateUI() {
double subtotal = getSubTotalPrice(basketProducts.getProducts());
double taxPrice = getTaxPrice(subtotal,order.getTax());
}
When I call this method in both events I have some NullPointerException because always one of object is null.
It's expected behaviour. It's because either
this.orderorthis.basketProductsis not yet initialized.You need to remember that a subscriber is always be called whenever you're posting an Event. For example, when you're calling the following:
then, the
onOrderEvent(Order order)subscriber will be called immediately. The following are happened within the above case:onOrderEvent(Order order)this.orderis initializedupdateUIis called withoutthis.basketProductsinitialized yetNullPointerExceptionis raised.A simple fix can be done by checking if both the this.order
orthis.basketProductsare already initialized before calling theupdateUI`. Something like this:I think the reason that make you slightly confused with the EventBus mechanism is the
stickyflag. Take a look http://greenrobot.org/eventbus/documentation/configuration/sticky-events/ for details about it.