Eventbus: Sticky events are received multiple times

Created on 25 Nov 2013  ·  3Comments  ·  Source: greenrobot/EventBus

When working with sticky events I noticed that I received events multiple times. This was the case where registering and posting of events happen at the same time. I had a quick look in the code. In the postSticky method I noticed that the lock on the stickyEvents object is released immediatly after putting a sticky event. Then the event is posted to the current listeners.
For registering, the listener is first registered to receive events and afterwards tries to get the sticky event. When it gets the sticky event, it will receive it. This means a listener can get an event twice:

  1. The first one because the listener is already registered and the postSticky post the event to the listeners.
  2. A second one because during registering the sticky event is already found that was placed by the postSticky
need to investigate

Most helpful comment

removeStickyEvent can fix this problem
EventBus.getDefault().removeStickyEvent(NotifyToJoinEvent.class);

All 3 comments

Did you solve your problem?

I used a quickfix. I overloaded the methods registerSticky(Object), registerSticky(Object, int), postSticky(Object) on the class EventBus. And made them synchronized so I avoid the race condition that I described above. Because it was a quick fix and maybe there is a better way of solving it, I didn't send a patch.

public class EventBusWithStickyFix extends EventBus {

@Override
public synchronized void registerSticky(Object subscriber) {
    super.registerSticky(subscriber);
}

@Override
public synchronized void registerSticky(Object subscriber, int priority) {
    super.registerSticky(subscriber, priority);
}

@Override
public synchronized void postSticky(Object event) {
    super.postSticky(event);
}

}

removeStickyEvent can fix this problem
EventBus.getDefault().removeStickyEvent(NotifyToJoinEvent.class);

Was this page helpful?
0 / 5 - 0 ratings

Related issues

liaohuyu picture liaohuyu  ·  4Comments

ANewAnonymous picture ANewAnonymous  ·  4Comments

cckroets picture cckroets  ·  16Comments

nschwermann picture nschwermann  ·  4Comments

gsteigert picture gsteigert  ·  5Comments