Skip to content

Support a Kotlin coroutines ThreadMode for Subscribe methods #706

Open
@frett

Description

@frett

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.

  • use runBlocking {} on an ASYNC subscriber which will provide a coroutine context, but this will still block the ASYNC thread until runBlocking completes and doesn't efficiently use threads.
  • don't make the subscriber suspendable, but instead launch a background coroutine from the subscriber method to do the long running processing.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions