kotlinsyntaxkotlin-coroutinessuspend

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


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()
    }

  }
}

Solution

  • The lambda's suspend modifier should be placed after the colon character, not before it. Example:

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