1. Overview
In this article, we will learn about the suspend function in Kotlin Android. To learn more about Kotlin coroutines, refer to our articles.
2. Kotlin coroutines & suspend functions
Basically, coroutines are computations that can be suspended without blocking a thread and simplifies asynchronous operations in Android.
Suspending functions are the hallmark of Kotlin coroutines. The suspension capability is the single most essential feature upon which all other Kotlin Coroutines concepts are built.
Suspending a coroutine means stopping it in the middle. When the coroutines are suspended, they return a Continuation
. Then, can continue from the point where it was stopped.
Notice that this differs from a thread, which you cannot save but only blocked. A coroutine is much more powerful. When suspended, it does not consume any resources. A coroutine can resume on a different thread, and a continuation can be serialized, deserialized, and then resumed.
3. Suspend function Kotlin Android
Suspending functions are functions that can suspend a coroutine. This means that they must be called from a coroutine (or another suspending function). In the end, they need to have something to suspend.
We use the suspend
modifier with functions that need to be run inside Coroutine. You can start, then pause a suspending function and resume it at a later time. They can execute a long-running operation and wait for it to complete without blocking.
The syntax of a suspending function is same as that of a regular function except for the addition of the suspend
keyword. It can take a parameter and have a return type. However, suspending functions can only be invoked by another suspending function or within a coroutine.
suspend fun myFunction() { println("Before") delay(1000) println("After") }
3.1. Under the hood
The compiler converts the suspend functions to another function without the suspend keyword, that takes an additional parameter of type Continuation<T>
.
fun myFunction(continuation: Continuation<*>): Any { println("Before") delay(1000) println("After") }
Continuation<T>
is an interface that contains two functions that are invoked to resume the coroutine with a return value or with an exception if an error had occurred while the function was suspended.
interface Continuation<in T> { val context: CoroutineContext fun resume(value: T) fun resumeWithException(exception: Throwable) }
4. Conclusion
To sum up, we have learned the suspend function in Kotlin Android.