Search code examples
javareflectionevent-busottogreenrobot-eventbus

Do GreenRobot's and Guava's EventBus use reflection?


Our Android app currently uses Otto EventBus, which uses reflection. We want to avoid the overhead of reflection, but keep the flexibility. Does Guava's event bus use reflection? What about GreenRobot's?

If they don't do they use code generation or something like that?


Solution

  • Otto was never nearly as feature-packed as GreenRobot's EventBus - no threading modes, for example, so it's good riddance. And Otto was deprecated in favor of RxJava - which is massive overkill for many projects (personal opinion).



    But in order to reduce reflection usage, GreenRobot EventBus 3.x is able to build an index in compilation time using APT rather than runtime reflection.

    http://greenrobot.org/eventbus/documentation/subscriber-index/


    Index Preconditions: Note that only @Subscriber methods can be indexed for which the subscriber AND event class are public. Also, due to technical limitations of Java’s annotation processing itself, @Subscribe annotations are not recognized inside of anonymous classes.

    buildscript {
        dependencies {
            classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
        }
    }
    
    
    
    apply plugin: 'com.neenbedankt.android-apt'
    
    dependencies {
        compile 'org.greenrobot:eventbus:3.0.0'
        apt 'org.greenrobot:eventbus-annotation-processor:3.0.1'
    }
    
    apt {
        arguments {
            eventBusIndex "com.example.myapp.MyEventBusIndex"
        }
    }
    

    And

    EventBus.builder().addIndex(new MyEventBusIndex()).installDefaultEventBus();
    // Now the default instance uses the given index. Use it like this:
    EventBus eventBus = EventBus.getDefault();