EventBus with Kotlin not working

8.6k views Asked by At

I am new to Android, and trying to send message from a Fragment to its container Activity using EventBus. However, I am getting error:

D/EventBus: No subscribers registered for event class com.app.todo.controllers.task.TaskListFragment$TaskCreateSelectEvent

Following is the code in Activity class related to EventBus:

public class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onTaskCreateSelectEvent(event: TaskListFragment.TaskCreateSelectEvent) {
        Log.d("TAG", "On Main Activity")
    }

    fun addFragment(fragment: Fragment) {
        val transaction = supportFragmentManager.beginTransaction()
        transaction.setCustomAnimations(R.anim.enter, R.anim.exit, R.anim.pop_enter, R.anim.pop_exit)
        transaction.add(R.id.task_fragment_container, fragment)
        transaction.addToBackStack(fragment.javaClass.simpleName)
        transaction.commit()
    }

    public override fun onStart() {
        super.onStart()
        EventBus.getDefault().register(this)
    }

    public override fun onStop() {
        super.onStop()
        EventBus.getDefault().unregister(this)
    }

}

Following is in Fragment class

public class TaskListFragment : Fragment() {
    private var fab: FloatingActionButton? = null

    public class TaskCreateSelectEvent {
        var fab: FloatingActionButton? = null
    }

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        var view = inflater!!.inflate(R.layout.task_list_fragment, container, false)
        fab = view.findViewById<FloatingActionButton>(R.id.fab)
        fab!!.setOnClickListener {
            val selectEvent = TaskCreateSelectEvent()
            EventBus.getDefault().post(selectEvent)
        }
        return view
    }
}

This is how library is added in build.gradle file.

apply plugin: 'kotlin-kapt'

dependencies {
    compile 'org.greenrobot:eventbus:3.0.0'
    kapt 'org.greenrobot:eventbus-annotation-processor:3.0.1' }

kapt {
    arguments {
        arg('eventBusIndex', 'com.app.todo.controllers.MyEventBusIndex')
    } 
}

Any idea what I am doing wrong?

2

There are 2 answers

1
Tobias On

I am new to Android ...

then you should better get familiar with dagger and rx instead. Event busses are a bad thing on android and often make things more complicated than necessary.

https://www.google.de/search?q=android+rxjava+instead+of+eventbus

2
Dominik On

try to change your subscribed method name to:

    onMessageEvent(event: TaskListFragment.TaskCreateSelectEvent)

but as the @Lord Flash suggested - use rxjava instead of eventbus. Take a look at PublishSubject/PublishProcessor (rx 2.0) classes