Skip to content

Commit 2543f6c

Browse files
Suspend function in kotlin
1 parent 1940d33 commit 2543f6c

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

Suspend function in Kotlin

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
Suspending functions are at the center of everything coroutines. A suspending function is simply a function that can
2+
be paused and resumed at a later time. They can execute a long running operation and wait for it to complete without blocking.
3+
4+
The syntax of a suspending function is similar to that of a regular function except for the addition of the suspend
5+
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.
6+
7+
suspend fun backgroundTask(param: Int): Int {
8+
// long running operation
9+
}
10+
11+
Under the hood, suspend functions are converted by the compiler to another function without the suspend keyword,
12+
that takes an addition parameter of type Continuation<T>. The function above for example, will be converted by the compiler to this:
13+
14+
fun backgroundTask(param: Int, callback: Continuation<Int>): Int {
15+
// long running operation
16+
}
17+
Continuation<T> is an interface that contains two functions that are invoked to resume the coroutine with a
18+
return value or with an exception if an error had occurred while the function was suspended.
19+
20+
interface Continuation<in T> {
21+
val context: CoroutineContext
22+
fun resume(value: T)
23+
fun resumeWithException(exception: Throwable)
24+
}

0 commit comments

Comments
 (0)