Home > Back-end >  Kotlin: How do you execute something as soon as a suspend function returns?
Kotlin: How do you execute something as soon as a suspend function returns?

Time:10-02

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>}

?

CodePudding user response:

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"
}

CodePudding user response:

A suspend fun is by definition a function that will return a result asynchronously.

If you want to get the result, you have two way :

Naive way using runBlocking

the runBlocking method allow you to write code in a lambda that will block the current thread and wait for the result of each suspend method.

In your case you could write :

runBlocking {
   val result = loadSomething()
}

Better way using coroutines

In fact, we don't really want to use runBlocking. Blocking the current thread can be really bad if it's the main thread, it will freeze the app.

You can launch a coroutine and execute the code in it. It will work the same way as the runBlocking code but will prevent it to be executed in the main thread.

For exemple, in a viewModel you have a viewModelScope which can use the launch method.

class MyViewModel: ViewModel() {
    val myResult: LiveData<YourType> = MutableLiveData()
    fun fetchSomething = viewModelScope.launch {
        val result = loadSomething()
        myResult.postValue(result)
    }
}

Here, we are using a coroutine to call the suspend method and posting the result in a liveData.

  • Related