I would like to express a suspend function as a ca...
# getting-started
d
I would like to express a suspend function as a callback:
Copy code
suspend fun getMyObject() : MyObject {
   ...
   return myObject
}

val myApp = myCallback { myObject ->
   /* code using myObject */
}
how should I write the function 
myCallback
?
w
Hey, so what are you trying to achieve? as I notice you want to execute the
block
but also return a value for
myApp
? For example (Using
String
as the
MyObject
):
Copy code
suspend fun getMyObject(): String {
        return "something"
    }

    suspend fun myCallback(block: suspend (String) -> String): String {
        return block(getMyObject())
    }

    val myApp = myCallback { myObject ->
        myObject
    }
This makes your
block
responsible to return the value to assign to
myApp
. If you want directly the value from
getMyObject
but ALSO execute the
block
with the value, can be something like this:
Copy code
suspend fun myCallback(block: suspend (String) -> Unit): String {
        return getMyObject().also { block(it) }
    }

    val myApp = myCallback { myObject ->
        // do something with myObject
    }
d
that’s great!!! thanks I wasn’t actually focused on
myCallback
returning a value
Note:
DKMPViewModel.getWebInstance()
is a suspend function
Actually I couldn’t make it work. The error is:
Copy code
Suspend function 'myComposeApp' should be called only from a coroutine or another suspend function
s
Start your main with
runBlocking { ...}
or declare your
suspend fun main()
as suspend.
c
Don't spam multiple channels.
d
Sorry, I had just posted a message in #coroutines, but somehow this channel is always the most helpful