androidkotlinannotationsgreenrobot-eventbus

GreenRobot EventBus subscribe based on API level


I'm attempting to subscribe to an EventBus event. Due to the parent class not existing in API level 23 and below, I'm in a situation where I need to conditionally subscribe to said event.

I realize that, through the use of build variants, it is possible to get around this, but I'm curious if there's a more elegant solution. The @RequiresApi annotation doesn't seem to have any effect (maybe stacking annotations doesn't work the way I expect it to).

Some simplified sample code:

class MyClass : OtherClass() {
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onSomeEvent(someEvent: SomeEvent) {
        // do some stuff
    }
}

Assuming OtherClass() is only available in API level 24+, the app will hang on the splash screen on lower API levels right after Dalvik or the ART realizes that the generated EventBusIndex references a broken class.


Solution

  • You could try to tweak MyClass somewhat to move the subscription to another object:

    class MyClass : OtherClass() {
        val subber = Subber()
    
        fun onSomeEventForRealz(someEvent: SomeEvent) {
            // do some stuff
        }
    
        inner class Subber {
            @Subscribe(threadMode = ThreadMode.MAIN)
            fun onSomeEvent(someEvent: SomeEvent) = onSomeEventForRealz(someEvent)
        }
    }
    

    You would also need to adjust your subscribe() and unsubscribe() calls to pass in subber instead of the MyClass instance itself.