Coroutines - Suspend functions

Coroutines - Suspend functions

Suspend functions

  • can be started , paused and resumed
  • it can be called from another suspend functions or a coroutine

code - suspend function

// coroutine to add two numbers 
private suspend fun doNumberAddition(varOne: Int, varTwo: Int): Int {
    delay(3000)
    return varOne.plus(varTwo)
}

The above suspend function is to add two numbers with the delay of 3 seconds

code

lifecycleScope.launch(Dispatchers.IO) {
    Log.d("Coroutines", "lifecycleScope : ${Thread.currentThread().name}")
    val result = doNumberAddition(10, 67)
    Log.d("Coroutines", "lifecycleScope : result - $result")
}

The above code does the following

  • The suspend function doNumberAddition launched inside a coroutine
  • ifecycleScope is used to launch this coroutine
  • he dispatcher used for this code is Dispatchers.IO

Output

17:11:21.271 D/Coroutines: Main : main
17:11:21.302 D/Coroutines: lifecycleScope : DefaultDispatcher-worker-1
17:11:24.307 D/Coroutines: lifecycleScope : result - 7

If we decomplie the above code

private final Object doNumberAddition(int varOne, int varTwo, Continuation var3) {...}

There is a parameter called Continuation which we can see in bytecode

Continuation

  • is ued to hold the context of the coroutine , so that when the suspend function resume , the Continuation will have the result and context

According to official documentation ,

/**
 * Interface representing a continuation after a suspension point that returns a value of type `T`.
 */
@SinceKotlin("1.3")
public interface Continuation<in T> {
    /**
     * The context of the coroutine that corresponds to this continuation.
     */
    public val context: CoroutineContext

    /**
     * Resumes the execution of the corresponding coroutine passing a successful or failed [result] as the
     * return value of the last suspension point.
     */
    public fun resumeWith(result: Result<T>)
}

So , in the above code

CoroutineContext - as we know this is about the context of coroutine , let's consider the didpatcher information is here , so that suspend function will run in the same threading policy when it is resumed .

Result - this is the result of suspend function itself

Quick review :

Suspend function can be started . paused and resumed

Uses the Continuation to pass the context and result within the suspend functions

Suspend function can be launched from another suspend function or a coroutine

Please leave your comments to improve.

Happy Coding