Skip to content

SharedFlow.emit() doesn't wait for a subscriber to complete collectingΒ #2603

Open
@j2esu

Description

@j2esu

SharedFlow doc says:

For example, the following class encapsulates an event bus that distributes events to all subscribers in a rendezvous manner, suspending until all subscribers process each event

So, with the following code

fun main() = runBlocking {
    val numbers = MutableSharedFlow<Int>()
    GlobalScope.launch {
        delay(1000)
        repeat(3) {
            println("emit $it")
            numbers.emit(it)
        }
    }
    GlobalScope.launch {
        numbers.collect {
            delay(1000)
            println("$it collected")
        }
    }.join()
}

we could expect the following output:

emit 0
0 collected
emit 1
1 collected
emit 2
2 collected

But the actual output is:

emit 0
emit 1
0 collected
emit 2
1 collected
2 collected

Seems like the flow has an extra 1 size buffer and doesn't suspend on first emit() call. Is it a bug, or I'm 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