【问题标题】:Passing coroutine function as function parameter将协程函数作为函数参数传递
【发布时间】:2026-02-04 01:00:02
【问题描述】:

我需要将协程函数作为参数传递给另一个函数。例如:

private fun handleIt(here: Long, call: (hereId: Long) -> Unit) {
            call(here)
}

然后从协程作用域:

GlobalScope.launch {
                        handleIt(3) { viewModel.doThings(hereId) }
                    }

viewModel 函数如下所示:

suspend fun doThings(hereId: Long) {
        withContext(coroutineContextProvider.io) {
            doSomething(hereId)
        }
    }

但是现在,我得到了错误:“只能在协程体内调用暂停函数。有什么建议吗?

【问题讨论】:

  • 示例没有多大意义。 doSomething() 与其他一切有什么关系?
  • 这不是真正的代码。它应该只是显示问题...

标签: kotlin coroutine higher-order-functions


【解决方案1】:

简单的解决方案是将块和handleIt 函数标记为暂停:

suspend fun handleIt(here: Long, call: suspend (hereId: Long) -> Unit) {
    call(here)
}

【讨论】:

  • 太棒了!不知道这个语法是否正确,谢谢!