Skip to content

incorrect Dispatchers.Main.immediate behavior #4276

@VladislavSumin

Description

@VladislavSumin

Run this code:

        // main thread here.
        println("1")
        val scope1 = CoroutineScope(Dispatchers.Main.immediate)
        scope1.launch {
            println("2")
            val scope2 = CoroutineScope(Dispatchers.Main.immediate)
            scope2.launch {
                println("3")
            }
            println("4")
        }
        println("5")

I expect the output to be 1 2 3 4 5 but in reality the output will be 1 2 4 3 5.

The documentation for Dispatchers.Main.immediate does not warn about such behavior, so I am inclined to consider this behavior incorrect.

This example may seem bad, but in real code we would not expect the behavior of a function called on mainThread to be different depending on whether it is called inside a coroutine:

fun sample() {
    val scope2 = CoroutineScope(Dispatchers.Main.immediate)
    scope2.launch {
        println("3")
    }
    println("4")
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions