greenrobot / EventBus

Event bus for Android and Java that simplifies communication between Activities, Fragments, Threads, Services, etc. Less code, better quality.
http://greenrobot.org/eventbus/
Apache License 2.0
24.67k stars 4.66k forks source link

Support a Kotlin coroutines ThreadMode for Subscribe methods #706

Open frett opened 1 year ago

frett commented 1 year ago

It would be nice if there was support for using a coroutines dispatcher to dispatch long running subscribe methods in the background. This would be similar in functionality to ThreadMode.ASYNC. But instead of using a thread pool where each subscribe consumes a thread until it completes, the subscribe method would be able to suspend execution and yield the thread to other subscribers to start processing.

How I'd imagine this would look in Kotlin code would be:

class Obj {
  @Subscribe(threadMode = ThreadMode.COROUTINE) // could also be ThreadMode.SUSPENDABLE
  suspend fun longRunningSubscriber(event: Event) {
    // do something
    // suspend for some long running IO
    // do something else
  }
}

Taking a quick look at the EventBus logic there are a couple things that would need to be implemented/updated.

  1. The logic that finds subscribe methods would need to be able to recognize suspendable methods.
    • When Kotlin code is compiled to Java, suspend methods have a Continuation parameter added to the Java method signature.
  2. a CoroutinesPoster (similar in concept to AsyncPoster) would need to be created that would dispatch the corresponding suspendable method using a coroutines Dispatcher.

If you don't want to include kotlin/coroutines logic in the main EventBus artifact, I would be fine if this was some sort of optional support that is only available if you import an additional module into the class path & add some configuration to the EventBus object that activates the additional module.

Currently there are a couple possible workarounds to get a coroutine context within a subscriber.

greenrobot-team commented 1 year ago

Thanks for the suggestion!