https://kotlinlang.org logo
#getting-started
Title
# getting-started
d

Daniele B

06/16/2021, 9:16 AM
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

wbertan

06/16/2021, 9:27 AM
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

Daniele B

06/16/2021, 9:30 AM
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

streetsofboston

06/16/2021, 11:33 AM
Start your main with
runBlocking { ...}
or declare your
suspend fun main()
as suspend.
c

CLOVIS

06/16/2021, 4:45 PM
Don't spam multiple channels.
d

Daniele B

06/16/2021, 9:52 PM
Sorry, I had just posted a message in #coroutines, but somehow this channel is always the most helpful
2 Views