Nico
Nico

Reputation: 123

Kotlin: How do you execute something as soon as a suspend function returns?

Is there the possibility to execute a code block directly after a suspend function returns?

Let's say we have a suspend function that sets some variable x that i want to use afterwards:

suspend fun loadSomething() {..}

Is there any way to do something like

loadSomething().whenDone {<use x somehow>}

?

Upvotes: 1

Views: 1290

Answers (1)

broot
broot

Reputation: 28362

Suspend functions are synchronous, so there is no need for such operators. You do this as normal:

loadSomething()
// use x

Full example:

var x: String? = null

suspend fun main() {
    loadSomething()
    println(x) // prints "loaded"
}

suspend fun loadSomething() {
    delay(500)
    x = "loaded"
}

Upvotes: 1

Related Questions