Kotlin: Can we use @Subscribe of EventBus (GreenRobot) in Kotlin?

风格不统一 提交于 2019-12-05 03:51:21

To use annotation processors with Kotlin, you need to use the Kotlin Annotation Processor tool (kapt).

Add this to your build.gradle:

apply plugin: 'kotlin-kapt'

According to GreenRobot (and confirmed by my testing), this is all you need to get @Subscribe.

  1. Make sure your event handler function with @Subscribe annotation is public
  2. In the build.gradle file add the code:

    apply plugin: 'kotlin-kapt'
    
    implementation "org.greenrobot:eventbus:3.0.0"
    kapt 'org.greenrobot:eventbus-annotation-processor:3.0.1'
    
  3. If you want to use Subscriber Index, you add the code to build.gradle too:

    kapt { arguments { arg('eventBusIndex', 'your-package.MyEventBusIndex') } }

You could use Square's Otto, which works the same way and works perfectly with Kotlin. Although, be careful as EventBuses are prone to overcomplicate Android code, and that's why they've deprecated the framework in favor of Rx.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!