Home > Software design >  Kotlin Unit and coroutine body
Kotlin Unit and coroutine body

Time:08-19

Assume there are some chained suspend functions like this.

suspend fun getData(): Boolean {
    return request().also {
        delay(1000)
    }
}

suspend fun request(): Boolean {
    return call()
}

suspend fun call(): Boolean {
    return run {
        delay(1000)
        true
    }
}

The above works allright. But if we convert the also block into a Unit param we will get an error: Suspension functions can be called only within coroutine body

suspend fun getData(): Boolean {
    return request {
        delay(1000) //the error
    }
}

suspend fun request(action: (Boolean) -> Unit): Boolean {
    return call().also(action)
}

Why is it so and is it possible to make the Unit inherit the coroutine body?

CodePudding user response:

You should make the lambda parameter suspend:

suspend fun request(action: suspend (Boolean) -> Unit): Boolean {

Now the lambda parameter has a suspending function type, but also doesn't take that, so you can't pass it in directly like also(action), you need to change it to:

return call().also { action(it) }

See also: how to pass suspend function as parameter to another function? Kotlin Coroutines

  • Related