Skip to content

Potential bug involving Undispatched and withContext #4523

@ListenableFuture

Description

@ListenableFuture

I ran into this issue where I have a method like the following:

suspend fun doSomeIo() = withContext(Dispatchers.IO) {
  // Code that should run on IO
}

The code should always run on the IO dispatcher and I think it should be guaranteed from the way I wrote it.

However, it turns out that if someone calls my function like so, it can actually run my code on a different thread (like the Android Main thread):

val ioScope = CoroutineScope(Dispatchers.IO + SupervisorJob())

// Starts on Main thread
ioScope.launch(start = CoroutineStart.UNDISPATCHED) {
  doSomeIo()
}

This seems to happen because they start it UNDISPATCHED, so it continues on the Main thread, which makes sense. However, when the withContext in doSomeIo is checked it sees it is the same dispatcher as their ioScope and so doesn’t dispatch again, even though it currently isn’t actually on the IO dispatcher.

This seems like a bug because as a code author of doSomeIo I can’t guarantee what thread my code is run on, and also the effect can actually go through multiple functions, classes, and files making it difficult to debug.

I was hoping to ask your team for their perspective on this. Thanks!

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