【问题标题】:Kotlin Unit and coroutine bodyKotlin 单元和协程体
【发布时间】:2022-08-18 20:04:58
【问题描述】:

假设有一些像这样的链接挂起函数。

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

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

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

以上工作正常。但是如果我们将also 块转换为Unit 参数,我们会得到一个错误: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)
}

为什么会这样,有没有可能让Unit继承协程体?

    标签: kotlin kotlin-coroutines


    【解决方案1】:

    您应该将 lambda 参数设为suspend

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

    现在 lambda 参数有一个暂停函数类型,但是also不接受,所以不能像also(action)那样直接传入,需要改成:

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

    另请参阅:how to pass suspend function as parameter to another function? Kotlin Coroutines

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-18
      • 2019-12-25
      • 2019-08-03
      • 2019-02-14
      • 2018-04-20
      • 2018-05-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多