Giter VIP home page Giter VIP logo

eventbus's Introduction

EventBus

EventBus is a publish/subscribe event bus for Android and Java.

Build Status Follow greenrobot on Twitter

EventBus...

  • simplifies the communication between components
    • decouples event senders and receivers
    • performs well with Activities, Fragments, and background threads
    • avoids complex and error-prone dependencies and life cycle issues
  • makes your code simpler
  • is fast
  • is tiny (~60k jar)
  • is proven in practice by apps with 1,000,000,000+ installs
  • has advanced features like delivery threads, subscriber priorities, etc.

EventBus in 3 steps

  1. Define events:

    public static class MessageEvent { /* Additional fields if needed */ }
  2. Prepare subscribers: Declare and annotate your subscribing method, optionally specify a thread mode:

    @Subscribe(threadMode = ThreadMode.MAIN)  
    public void onMessageEvent(MessageEvent event) {
        // Do something
    }

    Register and unregister your subscriber. For example on Android, activities and fragments should usually register according to their life cycle:

     @Override
     public void onStart() {
         super.onStart();
         EventBus.getDefault().register(this);
     }
    
     @Override
     public void onStop() {
         super.onStop();
         EventBus.getDefault().unregister(this);
     }
  3. Post events:

     EventBus.getDefault().post(new MessageEvent());

Read the full getting started guide.

There are also some examples.

Note: we highly recommend the EventBus annotation processor with its subscriber index. This will avoid some reflection related problems seen in the wild.

Add EventBus to your project

Available on Maven Central.

Android projects:

implementation("org.greenrobot:eventbus:3.3.1")

Java projects:

implementation("org.greenrobot:eventbus-java:3.3.1")
<dependency>
    <groupId>org.greenrobot</groupId>
    <artifactId>eventbus-java</artifactId>
    <version>3.3.1</version>
</dependency>

R8, ProGuard

If your project uses R8 or ProGuard this library ships with embedded rules.

Homepage, Documentation, Links

For more details please check the EventBus website. Here are some direct links you may find useful:

Features

Documentation

Changelog

FAQ

License

Copyright (C) 2012-2021 Markus Junginger, greenrobot (https://greenrobot.org)

EventBus binaries and source code can be used according to the Apache License, Version 2.0.

Other projects by greenrobot

ObjectBox (GitHub) is a new superfast object-oriented database.

Essentials is a set of utility classes and hash functions for Android & Java projects.

eventbus's People

Contributors

andob avatar chthai64 avatar f2prateek avatar friederbluemle avatar greenrobot avatar greenrobot-team avatar guoci avatar heinrichreimer avatar jnagels avatar joanzapata avatar justintuchek avatar leandros avatar mikosik avatar mormih avatar nbeloglazov avatar perfectcarl avatar stefanhoth avatar talklittle avatar william-ferguson-au avatar zsoltvilagos avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

eventbus's Issues

Dex Warnings

Seems when the device dex's the class files it throws a load of warnings..

[2012-11-03 00:53:00 - Moupp] ActivityManager: Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=com.moupp.android/.ui.activities.SplashActivity }
[2012-11-03 00:59:33 - Moupp] Dx
trouble processing:
[2012-11-03 00:59:33 - Moupp] Dx bad class file magic (cafebabe) or version (0033.0000)
...while parsing de/greenrobot/event/AsyncPoster.class
...while processing de/greenrobot/event/AsyncPoster.class
[2012-11-03 00:59:33 - Moupp] Dx
trouble processing:
[2012-11-03 00:59:33 - Moupp] Dx bad class file magic (cafebabe) or version (0033.0000)
...while parsing de/greenrobot/event/BackgroundPoster.class
...while processing de/greenrobot/event/BackgroundPoster.class
[2012-11-03 00:59:33 - Moupp] Dx
trouble processing:
[2012-11-03 00:59:33 - Moupp] Dx bad class file magic (cafebabe) or version (0033.0000)
...while parsing de/greenrobot/event/EventBus$1.class
...while processing de/greenrobot/event/EventBus$1.class
[2012-11-03 00:59:33 - Moupp] Dx
trouble processing:
[2012-11-03 00:59:33 - Moupp] Dx bad class file magic (cafebabe) or version (0033.0000)
...while parsing de/greenrobot/event/EventBus$2.class
...while processing de/greenrobot/event/EventBus$2.class
[2012-11-03 00:59:33 - Moupp] Dx
trouble processing:
[2012-11-03 00:59:33 - Moupp] Dx bad class file magic (cafebabe) or version (0033.0000)
...while parsing de/greenrobot/event/EventBus$3.class
...while processing de/greenrobot/event/EventBus$3.class
[2012-11-03 00:59:33 - Moupp] Dx
trouble processing:
[2012-11-03 00:59:33 - Moupp] Dx bad class file magic (cafebabe) or version (0033.0000)
...while parsing de/greenrobot/event/EventBus$BooleanWrapper.class
...while processing de/greenrobot/event/EventBus$BooleanWrapper.class
[2012-11-03 00:59:33 - Moupp] Dx
trouble processing:
[2012-11-03 00:59:33 - Moupp] Dx bad class file magic (cafebabe) or version (0033.0000)
...while parsing de/greenrobot/event/EventBus$PostCallback.class
...while processing de/greenrobot/event/EventBus$PostCallback.class
[2012-11-03 00:59:33 - Moupp] Dx
trouble processing:
[2012-11-03 00:59:33 - Moupp] Dx bad class file magic (cafebabe) or version (0033.0000)
...while parsing de/greenrobot/event/EventBus.class
...while processing de/greenrobot/event/EventBus.class
[2012-11-03 00:59:33 - Moupp] Dx
trouble processing:
[2012-11-03 00:59:33 - Moupp] Dx bad class file magic (cafebabe) or version (0033.0000)
...while parsing de/greenrobot/event/EventBusException.class
...while processing de/greenrobot/event/EventBusException.class
[2012-11-03 00:59:33 - Moupp] Dx
trouble processing:
[2012-11-03 00:59:33 - Moupp] Dx bad class file magic (cafebabe) or version (0033.0000)
...while parsing de/greenrobot/event/HandlerPoster.class
...while processing de/greenrobot/event/HandlerPoster.class
[2012-11-03 00:59:33 - Moupp] Dx
trouble processing:
[2012-11-03 00:59:33 - Moupp] Dx bad class file magic (cafebabe) or version (0033.0000)
...while parsing de/greenrobot/event/NoSubscriberEvent.class
...while processing de/greenrobot/event/NoSubscriberEvent.class
[2012-11-03 00:59:33 - Moupp] Dx
trouble processing:
[2012-11-03 00:59:33 - Moupp] Dx bad class file magic (cafebabe) or version (0033.0000)
...while parsing de/greenrobot/event/PendingPost.class
...while processing de/greenrobot/event/PendingPost.class
[2012-11-03 00:59:33 - Moupp] Dx
trouble processing:
[2012-11-03 00:59:33 - Moupp] Dx bad class file magic (cafebabe) or version (0033.0000)
...while parsing de/greenrobot/event/PendingPostQueue.class
...while processing de/greenrobot/event/PendingPostQueue.class
[2012-11-03 00:59:33 - Moupp] Dx
trouble processing:
[2012-11-03 00:59:33 - Moupp] Dx bad class file magic (cafebabe) or version (0033.0000)
...while parsing de/greenrobot/event/SubscriberExceptionEvent.class
...while processing de/greenrobot/event/SubscriberExceptionEvent.class
[2012-11-03 00:59:33 - Moupp] Dx
trouble processing:
[2012-11-03 00:59:33 - Moupp] Dx bad class file magic (cafebabe) or version (0033.0000)
...while parsing de/greenrobot/event/SubscriberMethod.class
...while processing de/greenrobot/event/SubscriberMethod.class
[2012-11-03 00:59:33 - Moupp] Dx
trouble processing:
[2012-11-03 00:59:33 - Moupp] Dx bad class file magic (cafebabe) or version (0033.0000)
...while parsing de/greenrobot/event/SubscriberMethodFinder.class
...while processing de/greenrobot/event/SubscriberMethodFinder.class
[2012-11-03 00:59:33 - Moupp] Dx
trouble processing:
[2012-11-03 00:59:33 - Moupp] Dx bad class file magic (cafebabe) or version (0033.0000)
...while parsing de/greenrobot/event/Subscription.class
...while processing de/greenrobot/event/Subscription.class
[2012-11-03 00:59:33 - Moupp] Dx
trouble processing:
[2012-11-03 00:59:33 - Moupp] Dx bad class file magic (cafebabe) or version (0033.0000)
...while parsing de/greenrobot/event/ThreadMode.class
...while processing de/greenrobot/event/ThreadMode.class

Is beta version in active testing?

Maven Central offers 2.1.0-beta-1 but it appears to be older than 2.0.2. Which is the best/safest version to use?

2.1.0-beta-1 doesn't appear to be in the github code and I can't see a dev branch.

EventBusPerformance failed with "NoClassDefFoundError"

05-27 13:57:20.184: E/AndroidRuntime(18893): FATAL EXCEPTION: main
05-27 13:57:20.184: E/AndroidRuntime(18893): java.lang.IllegalStateException: Could not execute method of the activity
05-27 13:57:20.184: E/AndroidRuntime(18893): at android.view.View$1.onClick(View.java:3082)
05-27 13:57:20.184: E/AndroidRuntime(18893): at android.view.View.performClick(View.java:3549)
05-27 13:57:20.184: E/AndroidRuntime(18893): at android.view.View$PerformClick.run(View.java:14400)
05-27 13:57:20.184: E/AndroidRuntime(18893): at android.os.Handler.handleCallback(Handler.java:605)
05-27 13:57:20.184: E/AndroidRuntime(18893): at android.os.Handler.dispatchMessage(Handler.java:92)
05-27 13:57:20.184: E/AndroidRuntime(18893): at android.os.Looper.loop(Looper.java:154)
05-27 13:57:20.184: E/AndroidRuntime(18893): at android.app.ActivityThread.main(ActivityThread.java:4944)
05-27 13:57:20.184: E/AndroidRuntime(18893): at java.lang.reflect.Method.invokeNative(Native Method)
05-27 13:57:20.184: E/AndroidRuntime(18893): at java.lang.reflect.Method.invoke(Method.java:511)
05-27 13:57:20.184: E/AndroidRuntime(18893): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
05-27 13:57:20.184: E/AndroidRuntime(18893): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
05-27 13:57:20.184: E/AndroidRuntime(18893): at dalvik.system.NativeStart.main(Native Method)
05-27 13:57:20.184: E/AndroidRuntime(18893): Caused by: java.lang.reflect.InvocationTargetException
05-27 13:57:20.184: E/AndroidRuntime(18893): at java.lang.reflect.Method.invokeNative(Native Method)
05-27 13:57:20.184: E/AndroidRuntime(18893): at java.lang.reflect.Method.invoke(Method.java:511)
05-27 13:57:20.184: E/AndroidRuntime(18893): at android.view.View$1.onClick(View.java:3077)
05-27 13:57:20.184: E/AndroidRuntime(18893): ... 11 more
05-27 13:57:20.184: E/AndroidRuntime(18893): Caused by: java.lang.NoClassDefFoundError: de.greenrobot.event.ThreadMode
05-27 13:57:20.184: E/AndroidRuntime(18893): at de.greenrobot.eventperf.TestSetupActivity.startClick(TestSetupActivity.java:64)
05-27 13:57:20.184: E/AndroidRuntime(18893): ... 14 more

synchronous calls

Hi,

I like your library but I was wondering if it would be possible for the post method to call the registered onEvent methods without being queued when called from an onEvent method.

I think it could be useful.

JB

throws Error question

Hi,

Looking at EventBus and

  private void postSingleEvent(Object event, boolean isMainThread) throws Error

and the section in post(..)

 try {
    while (!eventQueue.isEmpty()) {
        postSingleEvent(eventQueue.remove(0), isMainThread);
    }
 } finally {
    isPosting.value = false;
 }

is there a reason for catching all Errors and dropping them (by having no catch)?

I only came accross this as I was using testing and this resulted in an AssertionError getting lost so I was getting a false positive. I would like to remove this but wondered if I was missing something?

Thanks

Notifications support

It would be great if EventBus would support some kind of fallback method when the UI can not be reached. In the most cases apps would want other components to do something in the background. The result gets delivered via an EventBus but what if the UI is no longer available. The app would possibly show a notification. After having tested all the different EventBus libraries I came back to the plain old android broadcasts. (one BroadcastReceiver in the activity and another BroadcastReceiver in the background having the lower priority) Depending on the availability of the UI the result gets handled correctly.

Am I missing something or is an event bus not the correct way to reach the above mentioned goal in this case and the broadcast pattern is still the most elegant one?

StickyEvent not subscribed via BaseEventType

Current Status

  1. I'm using EventBus 2.0.2
  2. I have "RefreshEvent" class which is extending "BaseEvent".
  3. And I registered current activity to get that sticky event like this.
EventBus.getDefault().registerSticky(this);

Here's the question.

  1. this works.
public void onEvent(RefreshEvent event) {} 
  1. but, this doens't work.
public void onEvent(BaseEvent event) {}

I looked into the source code. and here are some lines from EventBus.java @ line 255.

        if (sticky) {
            Object stickyEvent;
            synchronized (stickyEvents) {
                stickyEvent = stickyEvents.get(eventType);
            }
            if (stickyEvent != null) {
                postToSubscription(newSubscription, stickyEvent, Looper.getMainLooper() == Looper.myLooper());
            }
        }

When public void onEvent(BaseEvent event) {} is declared, the eventType is "BaseEvent", not "RefreshEvent". So it fails to get sticky event from "stickyEvents" map object.

Is it intended? or a bug?

Lot of exceptions

I keep getting these exceptions when the fragment is not event displayed yet.

x.eventbus.RegulationTimingsEvent to subscribing class class x.ui.dashboard.DashboardDetailFragment
02-21 14:56:03.062: E/Event(1270): java.lang.IllegalStateException: Fragment MyFragment{52818788} not attached to Activity

NPE at postSingleEvent(Object event, PostingThreadState postingState) throws Error

I have implemented EventBus concept in my project, It works fine.
But I am facing one issue, When I am getting my object as null due to some problem at server side. It is throwing NPE at line 459 in EventBus.java class.

private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
Class<? extends Object> eventClass = event.getClass();
:
:
:

}

Can you please suggest what will be the best solution approach, If my object is null.

Thanks,
Abhi

Feature suggestion: add ordered broadcast equivalent

A fairly clean pattern for a service to either update the foreground UI or raise a Notification is to use an ordered broadcast. It'd be nice to have an in-process-only equivalent of this, and LocalBroadcastManager doesn't do ordered broadcasts.

Have you considered a variation on an EventBus event that works like ordered broadcasts?

Thanks!

Event.cancelEventDelivery fire event again

 new PostThreadEventListener<KeyEventWrap>() {
        @Override
        protected void process(KeyEventWrap event) {
            if (slidingPaneLayout.isSlideable()
                    && !slidingPaneLayout.isOpen()
                    && event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
                //call this method,fire this event listener again
                ((Activity) getSupportActivity()).cancelEventDelivery(event);
                slidingPaneLayout.openPane();
            }
        }
    };

public abstract class PostThreadEventListener<E> extends EventListener<E> {
    public final void onEvent(E event) {
        doProcess(event);
    }
}

public abstract class EventListener<E> {
    protected abstract void process(E event);

    protected boolean isCanceled(E event) {
        if (event instanceof CanCancelEvent)
            return ((CanCancelEvent)event).isCanceled();
        return false;
    }

    protected void doProcess(E event){
        //if (!isCanceled(event)){
            process(event);
       // }
    }
}

public class Activity extends org.holoeverywhere.app.Activity {

    protected final EventBus eventBus;

    public Activity() {
        super();
        eventBus = new EventBus();
    }

 ....

   public void cancelEventDelivery(Object event) {
      if (event instanceof CanCancelEvent) {
          ((CanCancelEvent) event).cancel();
      }
      eventBus.cancelEventDelivery(event);
   }

....

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        CanCancelEvent _event = new KeyEventWrap(event);
        eventBus.post(_event);
        if (_event.isCanceled()) {
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }
}

Version 2.1.0

Are your released version 2.1.0 ?
I found commits with version 2.1.0 final.

When this version uploaded to maven repo?
Where changelog?

Eventbus: Todos being worked on?

I don't know if this is the right place to post this but:
When is the debug related feature request (initiated a year ago) actually going to get done?

Additionally there are a number of ToDo's awaiting completion on the main EventBus page: https://github.com/greenrobot/EventBus

..including:
1.) Subscriber priorities and ordered event delivery
TODO. For now, this is just the javadoc for the method register(Object subscriber, int priority): Like register(Object) with an additional subscriber priority to influence the order of event delivery. Within the same delivery thread (ThreadMode), higher priority subscribers will receive events before others with a lower priority. The default priority is 0. Note: the priority does NOT affect the order of delivery among subscribers with different ThreadModes!
2.) Canceling further event delivery
TODO. For now, this is just the javadoc for the method cancelEventDelivery(Object event): Called from a subscriber's event handling method, further event delivery will be canceled. Subsequent subscribers won't receive the event. Events are usually canceled by higher priority subscribers (see register(Object, int)). Canceling is restricted to event handling methods running in posting thread ThreadMode.PostThread.
3.) There is also a ToDo placeholder under "Example" - any idea when a full fledged example will be forthcoming?

I know there is a some test code associated with the EventBus source code repository, but it would be helpful to have a fully developed example that really puts the EventBus code through its paces (hopefully using Async threading in an optimal way).

Note: I found EventBus through this Stack Overflow thread:
http://stackoverflow.com/questions/18787554/populate-ui-from-local-db-table-initially-then-if-webserivice-has-new-data-upda

..which has a link to a Google I/O Rest pattern design:
http://stackoverflow.com/questions/9112658/google-io-rest-design-pattern-finished-contentprovider-and-stuck-now

I would love to see a good implementation of this with EventBus as it's "Example", because there are not many good open source examples where sqlite databases are "maintained" (updated) from remote server based sqlite databases (or even using a large remote MySQL database which downloads, real time, into a an updated locally based sqlite file).

Could EventBus class instance by a Tag

When login or signout, I need to notify some thread . So I may create a object at login thread like that

EventBus loginBus = EventBus.getInstance("login");

/-----------------------------------
and then some work thread like loading background data or notify login activity success or failed. The code like that

EventBus loginBus = EventBus.getInstance("login");
loginBus.register(User.class);

Does this a better way to use a Global EventBus?

Canceling Events only work partly

If you call EventBus.cancelEventDelivery() the 'event' won't be canceled completely. Only subscribers, who have subscribed to exactly that event class (and not a parent one of that) won't get notified. If you have e.g. an onEvent(Object ev) listener and canceling sending of MyCustomEvent in an onEvent(MyCustomEvent) the onEvent(Object) method will still receive it. This is (imho) pretty unexpected behavior.

The error lies here: https://github.com/greenrobot/EventBus/blob/master/EventBus/src/de/greenrobot/event/EventBus.java#L482

Your break only break out the inner loop (subscribers for this class) and not the outer loop (all parent classes of the current event). You should also break out of the outer for loop.

Didn't know if you wish a labeled loop or putting the abort to the for condition, that's why I didn't send a pull request (and because it's anyway such a small change).

Unfortunately I didn't find a workaround till this is fixed, to really cancel an event. It seems like you have to keep an own list of canceled events if you use event hierarchy.

I hope the fix can be published soon :-) Thanks guys for the great lib.

Ill-advised or mistaken usage of core class (java.* or javax.*)

I get Android Dex: [lightpaper] trouble processing "javax/xml/namespace/QName.class" during compilation when I add EventBus as a maven dependency:

<dependency>
        <groupId>de.greenrobot</groupId>
        <artifactId>eventbus</artifactId>
        <version>2.0.1</version>
</dependency>

I also tried excluding EventBus's dependencies:

<exclusions>
            <exclusion>
                <artifactId>junit</artifactId>
                <groupId>junit</groupId>
            </exclusion>
            <exclusion>
                <artifactId>android</artifactId>
                <groupId>android</groupId>
            </exclusion>
            <exclusion>
                <groupId>com.google.android</groupId>
                <artifactId>support-v4</artifactId>
            </exclusion>
            <exclusion>
                <artifactId>android-test</artifactId>
                <groupId>com.google.android</groupId>
            </exclusion>
            <exclusion>
                <groupId>com.google.android</groupId>
                 <artifactId>annotations</artifactId>
            </exclusion>
</exclusions>

But no luck, I get the same error.

I'm using intelliJ 12 but I don't think that makes any difference.

"removeAllStickyEvents" method

When I have exited my app with the back button, and come back in, the eventbus still have sticky events in it. Can you give me a pointer or two as to why this may be? Could it be because I missed an unregister somewhere?

Register to generic type events

Hi, I'm currently using EventBus in my app. I really like it it makes stuff much simpler.
I'm just facing a small issue which is an edge case I guess.

I would like to subscribe to generic classes, how do I do that:

public onEvent(MyEvent<A> event) {
// Issue: I receive all events of the class MyEvent, event stuff like MyEvent<B>
}

POJO unregister question

Hi,

I would like to register a POJO object in EventBus.
It's easy - just call EventBus.getDefault().register(this) in constructor.

However I don't see the way to unregister that object before it is garbage collected.
Is it possible? Is it necessary?

Debug mode to access a poster's stack

Sometimes it would nice to know who posted the event, e.g. when an exception is thrown or while debugging. In some debug configuration, EventBus could store the poster and the callstack of post() until the event is delivered.

Weak reference to the subscriber

EventBus should keep a weak reference to the subscriber so registration aren't leaking objects when unregister is never called.

ProGuard configuration

I'd like to know if there's a better way but I had to add this to my proguard-project.txt file to stop the onEvent methods being stripped out:

-keepclassmembers class ** {
    public void onEvent(**);
}

Whatever the best method is should be added to the documentation.

NoSubscriberEvent is not called after unregister

I make a example testcast using EventBusNoSubscriberEventTest.java (in EventBusTest)

public class EventBusNoSubscriberEventTest2 extends AbstractEventBusTest {
    public void testNoSubscriberEvent() {

        eventBus.register(this, NoSubscriberEvent.class);
        eventBus.register(this, String.class);
        eventBus.post("Foo");
        String event = (String) lastEvent;
        assertEquals("Foo", event);
        eventBus.unregister(this, String.class);

        eventBus.post("Bar");
        assertEquals(NoSubscriberEvent.class, lastEvent.getClass());
        NoSubscriberEvent noSub = (NoSubscriberEvent) lastEvent;
        assertEquals("Bar", noSub.originalEvent);
    }

    public void onEvent(NoSubscriberEvent event) {
        trackEvent(event);
    }

    public void onEvent(String message) {
        trackEvent(message);
    }
}

This testcast fail. (lastEvent type is not NoSubscriberEvent)

expected:<class de.greenrobot.event.NoSubscriberEvent> but was:<class java.lang.String>

The cause of this problem is here

private void postSingleEvent(Object event, boolean isMainThread) throws Error {
    ...
        if (subscriptions != null) {
            for (Subscription subscription : subscriptions) {
                postToSubscription(subscription, event, isMainThread);
            }
            subscriptionFound = true;
        }
    ...
}

After unregister subscriptions can be a empty list (not null)

Allow checking if subscriber is already registered (isRegistered)

Should there be a "isRegistered()" method call to use in onResume() so I can check if the bus has been registered before registering?

Reason I ask is because of the following.

  1. Assume ActivityFragments is an Activity that holds two panels, left and right, which we call LeftFragment and RightFragment.

  2. ActivityFragments launches and in onCreate, launches both fragments.

  3. In my case, the RightFragment always finish launching even before ActivityFragment has moved to the onResume() state where normally the bus would be registered.

Because RightFragments completes before ActivityFragment can register the bus in onResume() , ActivityFragment can miss events from RightFragment.

So, I move register() bus call to ActivityFragment's onCreate() code which fixes the chicken and egg problem but this fails the onPause() and onResume() cycles where Activity is no longer registered to the bus.

Now I try to fix both cases, and have both bus registering during onCreate() and onResume() but this causes "already registered" exception in onResume().

Is there a way to check current registration problem without resorting to try {} catch {} code?

Sticky events are received multiple times

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

eventType for Template is not recognized

Here have two types of event callbacks. It seems EventBus can not differentiate them.

public void onEventMainThread(List<Type1> list) {
}
public void onEventMainThread(List<Type2> list) {
}

Could not dispatch event

I'm likely doing something wrong.. but I have been trying to debug this for almost 10 hours now... about ready to give up.

I have a setup like this:

Activity:
onCreate:
- mView = findViewById(R.id.view)
- register subscriber
- start event poster

onEventMainThread
-mView.setVisibility(View.GONE)

Event Poster:
Events are posted inside a runnable that is executed by a cached thread pool.

I get this exception:
Could not dispatch event: class com.example.MyEvent to subscribing class class com.example.MyActivity
java.lang.NullPointerException
at mView.setVisibility

Somehow mView is null. It's not, as I can call "mView.setVisibility(View.GONE)" in onCreate. Is this somehow a bug with EventBus?

Get callback when Sticky event is removed

In the case where a sticky event is being used to flag a long running process, like some long running network sync, it would be nice to listen for the event to be removed.

I could add a second event "SyncCompleted" and post that at the end - but if we're already using a sticky event to flag this long running process app wide it would be nice to simply watch for that event to go away.

Multiple registration of the same Fragment

Hej,

I have a ViewPager which holds several fragments of the same type. In this fragment i would like to subscribe to some Events, but it seems that the EventBus can only handle one registration of a type, so i always get an exception that this fragment is already registered. So my question is, how can i subscribe multiple objects of the same class?

Invalid event calls due to generics type erasure

I love EventBus and often post data to interested parties without specifying a simple class, instead relying on EventBus' behaviour to find the correct onEvent method based on the data type.

However, in determining whether an onEvent method matches the thrown event data type, generics are not considered. For example:

    List<String> strings = Arrays.asList("one", "two");
    EventBus.getDefault().post(strings);

will be caught by a method such as

public void onEventMainThread(List<Integer> numbers) {
    // The next line will cause a cast exception
    numbers.get(0).intValue();
}

I haven't (yet) looked at the code, but I suspect that this is because the immediate type is the same, as the generic signature is erased. EventBus should either 1) handle this case properly, or 2) if not possible (elegantly, due to java limitations) throw a relevant warning when posting data of such a type or 3) at least mention this limitation in the documentation.

Does this really need to be a library app?

That is basically it. I doesn't have (nor need) any screens, strings, or automobiles. If you can just make it a jar that would be more sensible and then putting in Maven won't be such a hassle, pom-wise that is.

Support library maven dependency

Currently version 2.1.0-beta1 and 2.0.1 in maven repository depends on support-v4-r7. This creates a problems since this is old version of support library and I can't use newer one in my projects in same gradle build script.

As a workaround I found only excluding this dependency from EventBus

dependencies {
    compile 'com.android.support:support-v4:18.0.+'
...
    compile ('de.greenrobot:eventbus:2+') {
        exclude module: 'support-v4'
    }
...
}

Registrations can be dropped due to internal lazy initialization races

At present (2.0.2) all registrations end up in the internal register(Object,SubscriberMethod,boolean) method. Unfortunately there are some concurrency problems surrounding the subscriptionsByEventType and typesBySubscriber maps that this method maintains:

  1. These maps aren't thread-safe. This is a basic concurrency issue.
  2. Even if the maps were thread-safe the lazy initialization algorithm is not. In particular when simultaneously registering listeners for the same type of event, more than one call may try to create the initial array for that type and discard competitors in the process.

We're observing these errors on occasion.

Workarounds at the present are:

  • At the very least wrap calls to register listeners in a synchronized block. The eventbus itself is suitable for synchronizing on.
  • For complete correctness extend this to also wrap calls to post events and unregister listeners.

Multiple Registration

I ran into an issue of the same object being able to register multiple times and in turn a single event is calling onEvent() multiple times. It seems like if I register an already registered object the EventBus should just ignore the register call.

removeStickyEvent(...) does not remove event the first time.

I'm noticing a behavior where [EventBus.getDefault()].removeStickyEvent(...) does not remove the event immediately, but follow-up calls do. This occurs with both usages (event instance and class type). Is this a bug? Or is there a scenario where this can occur that I am not understanding?

EventBusMultithreadedTest failed with "already registered"

02-11 18:45:08.750: I/TestRunner(16666): started: testSubscribeUnSubscribeAndPostMixedEventType(de.greenrobot.event.test.EventBusMultithreadedTest)
02-11 18:45:08.800: W/Event(16666): Subscriber to unregister was not registered before: class de.greenrobot.event.test.EventBusMultithreadedTest$SubscribeUnsubscribeThread
02-11 18:45:08.800: W/dalvikvm(16666): threadid=47: thread exiting with uncaught exception (group=0x41d3b2a0)
02-11 18:45:08.840: E/AndroidRuntime(16666): FATAL EXCEPTION: Thread-60258
02-11 18:45:08.840: E/AndroidRuntime(16666): de.greenrobot.event.EventBusException: Subscriber class de.greenrobot.event.test.EventBusMultithreadedTest$SubscribeUnsubscribeThread already registered to event class java.lang.Object
02-11 18:45:08.840: E/AndroidRuntime(16666): at de.greenrobot.event.EventBus.subscribe(EventBus.java:239)
02-11 18:45:08.840: E/AndroidRuntime(16666): at de.greenrobot.event.EventBus.register(EventBus.java:175)
02-11 18:45:08.840: E/AndroidRuntime(16666): at de.greenrobot.event.EventBus.register(EventBus.java:146)
02-11 18:45:08.840: E/AndroidRuntime(16666): at de.greenrobot.event.test.EventBusMultithreadedTest$SubscribeUnsubscribeThread.run(EventBusMultithreadedTest.java:233)

Post to a special subscriber (feature request)

It would be nice to have a method post(Object event, Object subscriber) to be able to post an event only to a specific subscriber. Why not just calling methods instead of posting to a specific subscriber? The above method could still use the method name to detect the thread mode (end event hierarchy), what you would otherwise have to do by hand.

Let exceptions crash the app

Hi, if I have an Exception that would normally crash the app within the onEvent callback method the app doesn't crash and the exception is logged by EventBus.
Is there a way to change that behaviour to the default one (exception -> crash) ?

onEventMainThread fired twice

Tested library version: 2.0.2

I have view component, it have onEventMainThread and one time register to bus.
From background thread one time fire event, but bust invoke onEventMainThread twice.

I suspect there is an error in the processing of thread -> main thread.

By the logs:
register - 1 time
post - 1 time
onEvent - 2 times

Argument is used unique type of event.

Order/Priority

I miss only one feature, It's an priority of subscribers.

Eventbus register fails in android 2.3

Hi, Eventbus register fails in android 2.3 with exception:
797-797/com.vandzi.eventbustest E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NoClassDefFoundError: de.greenrobot.event.EventBus
at com.vandzi.eventbustest.MainActivity.onResume(MainActivity.java:28)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1150)
at android.app.Activity.performResume(Activity.java:3832)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2110)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2135)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1668)
at android.app.ActivityThread.access$1500(ActivityThread.java:117)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3683)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
at dalvik.system.NativeStart.main(Native Method)

You can find example project at https://dl.dropboxusercontent.com/u/58420656/EventbusTestProject.zip

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.