Skip to content

Coroutines/Flow vs add/remove listener (synchronous execution) #3506

Open
@valeriyo

Description

@valeriyo
  1. Consider the traditional "add/remove listener" pattern, with synchronous event handlers:
interface MyEventListener {
  fun handle(myEvent: MyEvent)
}

fun add(listener: MyEventListener)
fun remove(listener: MyEventListener)
  1. With RxJava, the same can be accomplished with:
val myEvent: Observable<MyEvent>

because RxJava is synchronous by default. (To opt-out from synchronous execution, a subscriber can apply observeOn with some Scheduler - but this is not what we're trying to do here.. we really want synchronisity.)

  1. With coroutines, this would be the analogue to the RxJava solution:
val myEvent: Flow<MyEvent>

However, coroutines are asynchronous by default, and there seems to be no way to make their execution synchronous (reliably). Neither the CoroutineStart parameter of launch, nor Main.immediate guarantee that the execution will be synchronous in all cases.

The Main.immediate is strange in particular, because it is "immediate" only under perfect conditions:

  1. "dispatcher that executes coroutines immediately when it is already in the right context"
  2. "dispatcher is safe from stack overflows and in case of nested invocations forms event-loop"

Am I missing something?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions