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() } } }
It can take a parameter and have a return type. However, suspending functions can only be invoked by another suspending function or within a coroutine.
We just have to use the suspend keyword. Note: Suspend functions are only allowed to be called from a coroutine or another suspend function. You can see that the async function which includes the keyword suspend. So, in order to use that, we need to make our function suspend too.
BLOCKING: Function A has to be completed before Function B continues. The thread is locked for Function A to complete its execution. SUSPENDING: Function A, while has started, could be suspended, and let Function B execute, then only resume later. The thread is not locked by Function A.
Note that these xxxAsync functions are not suspending functions. They can be used from anywhere. However, their use always implies asynchronous (here meaning concurrent) execution of their action with the invoking code. // but waiting for a result must involve either suspending or blocking.
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() } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With