how to pass suspend function as parameter to another function? Kotlin Coroutines
Asked Answered
D

1

63

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

  }
}
Dawes answered 28/4, 2019 at 3:6 Comment(0)
D
135

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()
    }
  }
}
Dawes answered 28/4, 2019 at 3:22 Comment(2)
Code only answers are discouraged. Please add some explanation as to how this solves the problem. From ReviewMonolithic
Thx your very much, you help me to make code more clear!Decoration

© 2022 - 2024 — McMap. All rights reserved.