将协程函数作为函数参数传递

Fab*_*ASP 1 coroutine higher-order-functions kotlin

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

private fun handleIt(here: Long, call: (hereId: Long) -> Unit) {
            call(here)
}
Run Code Online (Sandbox Code Playgroud)

然后从协程范围:

GlobalScope.launch {
                        handleIt(3) { viewModel.doThings(hereId) }
                    }
Run Code Online (Sandbox Code Playgroud)

viewModel 函数如下所示:

suspend fun doThings(hereId: Long) {
        withContext(coroutineContextProvider.io) {
            doSomething(hereId)
        }
    }
Run Code Online (Sandbox Code Playgroud)

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

Ale*_*hin 7

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

suspend fun handleIt(here: Long, call: suspend (hereId: Long) -> Unit) {
    call(here)
}
Run Code Online (Sandbox Code Playgroud)