Skip to content

Add doBlocking() utility method for running coroutines. #4440

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from

Conversation

kevinhwang
Copy link

This is a useful utility method used in places where you want to run a coroutine for its side effect.

E.g.,

fun main() = doBlocking {
  // ...
}
@Test
fun myTest() = doBlocking {
  // ...
}

With runBlocking(), if the last line of the coroutine block being run doesn't evaluate to Unit, e.g.:

fun main() {
  runBlocking {
    // ...
    Unit
  }
}

the compiler will complain about being unable to infer the type variable T of the block. Inserting a "return value" of Unit at the end is necessary to tell the compiler the block's return type.

Similarly, if you do

@Test
fun myTest() = runBlocking {
  // ...
   Unit
}

without the explicit Unit "return value" at the end, if the last line evaluates to a non-unit type, you'll get a type mismatch error, or the compiler will infer myTest()'s return type to be non-Unit.

@dkhalanskyjb
Copy link
Collaborator

The expected way to use runBlocking in main is

fun main() {
    runBlocking {
        // your code
    }
}

the compiler will complain about being unable to infer the type variable T of the block.

Could you provide a specific example?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants