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

3

9

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?

Hankhanke answered 20/4, 2016 at 12:34 Comment(6)
How do you post your Event? Have your registered eventbus in your activity? Please add more informatiion.Danielladanielle
github.com/greenrobot/EventBus/issues/286Garrot
I have register onResume, and unregister onPause. The same post of event could be capture on another class in Java.Hankhanke
Try to register in onStart and unregister in onStop. Maybe your event is fired before you register to eventbus.Thorlay
Can I know how you solve the issue. I am facing a similar problem.Eulalia
onEvent() function should be publicSequester
A
5

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.

Ahrendt answered 30/8, 2017 at 14:40 Comment(1)
Since the EventBus 3.1.1, we don't need to add this anymore. Anyway, this is the correct workaround.Korry
H
4
  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') } }

Harpoon answered 26/9, 2017 at 11:31 Comment(0)
G
0

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.

Gossip answered 13/6, 2016 at 20:28 Comment(1)
This project is deprecated in favor of RxJava and RxAndroid. These projects permit the same event-driven programming model as Otto, but they’re more capable and offer better control of threading. If you’re looking for guidance on migrating from Otto to Rx, this post is a good start. blog.kaush.co/2014/12/24/…Indeterminate

© 2022 - 2024 — McMap. All rights reserved.