how to pass suspend function as parameter to another function? Kotlin Coroutines

别等时光非礼了梦想. 提交于 2020-03-14 07:07:09

问题


I want to send suspending function as a parameter, but it shows " Modifier 'suspend' is not applicable to 'value parameter" . how to do it?

fun MyModel.onBG(suspend bar: () -> Unit) {
  launch {
    withContext(Dispatchers.IO) {
        bar()
    }

  }
}

回答1:


Lambda's suspend modifier should be placed after the colon character, not in front. Example:

fun MyModel.onBG(bar: suspend () -> Unit) {
  launch {
    withContext(Dispatchers.IO) {
      bar()
    }
  }
}


来源:https://stackoverflow.com/questions/55886676/how-to-pass-suspend-function-as-parameter-to-another-function-kotlin-coroutines

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!