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

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-10 02:26:55

问题


My onEvent in a fragment as below, capturing the authentication of the activity, in my Kotlin function. However, I can't get that onEvent triggered.

@Subscribe
fun onEvent(event: AuthenticationEvent) {
    if (event.isAuthenticated) {
        startFragment(signInFragment, SignInFragment.TAG)
    } else {
        startFragment(signOutFragment, SignOutFragment.TAG)
    }
}

In my build.gradle file, I have add this

compile 'org.greenrobot:eventbus:3.0.0'

Is there anything I need to do to get this trigger?


回答1:


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.




回答2:


  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') } }




回答3:


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.



来源:https://stackoverflow.com/questions/36743968/kotlin-can-we-use-subscribe-of-eventbus-greenrobot-in-kotlin

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