Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()     }    } } 
like image 774
Nurseyit Tursunkulov Avatar asked Apr 28 '19 03:04

Nurseyit Tursunkulov


People also ask

Can you run a suspend function outside of a coroutine or another suspending function?

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.

How does Kotlin handle suspend function?

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.

What is the difference between suspending vs blocking in Kotlin?

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.

Is async a suspend function Kotlin?

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.


1 Answers

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()     }   } } 
like image 115
Nurseyit Tursunkulov Avatar answered Sep 30 '22 17:09

Nurseyit Tursunkulov