Subscriber Index

Contents

Since EventBus 3.0

Using a subscriber index avoids expensive look-ups of subscriber methods at run time using reflection. Instead, the EventBus annotation processor looks them up at build time.

It is recommended to use the index for Android apps in production. It is faster and avoids crashes due to reflection (see reported issues due to NoClassDefFoundError).

Index requirements

  • The @Subscribe method and its class must be public.
  • The event class must be public.
  • @Subscribe can not be used inside of anonymous classes.

Note: When EventBus cannot use an index, e.g. if the above requirements are not met, it will fall back to reflection at run time. This ensures @Subscribe methods receive events even if they are not part of the index.

How to generate the index

Java: using annotationProcessor

For plain Java projects (not Android) this requires Gradle 5.2 or newer.

In your apps build.gradle, add the eventbus-annotation-processor dependency using the annotationProcessor configuration. Then configure the package and name of the index class that should be generated by adding the eventBusIndex processor option.

Kotlin: using kapt

In your apps build.gradle, add the eventbus-annotation-processor dependency using the kapt configuration. Then configure the package and name of the index class that should be generated by adding eventBusIndex as a kapt argument.

How to use the index

Build the project at least once to generate the index class specified with eventBusIndex.

Then, e.g. in your Application class, use EventBus.builder().addIndex(indexInstance) to pass an instance of the index class to EventBus.

Use EventBusBuilder.installDefaultEventBus() to set the EventBus with index as the instance returned by EventBus.getDefault().

Indexing your Libraries

Libraries can ship an EventBus index. To use the index of a library, for each library call EventBusBuilder.addIndex(indexInstance) with an instance of its index class.

Spread the love