Suspending functions in Kotlin are special functions that can be paused and resumed later without blocking the thread. They can only be called from another suspending function or within a coroutine.
suspend fun printMessage() {
println("Task started")
delay(1000)
println("Task finished after 1 second")
}
GlobalScope.launch {
printMessage()
}
Output:
Task started
Task finished after 1 second
suspend fun fetchData(): String {
delay(2000)
return "Data fetched successfully"
}
GlobalScope.launch {
val result = fetchData()
println(result)
}
Output:
Data fetched successfully (after 2 seconds delay)
suspend fun taskOne() {
println("Task 1 started")
delay(1000)
println("Task 1 finished")
}
suspend fun taskTwo() {
println("Task 2 started")
delay(1000)
println("Task 2 finished")
}
GlobalScope.launch {
taskOne()
taskTwo()
}
Output:
Task 1 started
Task 1 finished
Task 2 started
Task 2 finished
private val TAG: String = "KOTLINFUN"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main2)
CoroutineScope(Dispatchers.Main).launch {
task1()
}
CoroutineScope(Dispatchers.Main).launch {
task2()
}
}
suspend fun task1() {
Log.d(TAG, "STARTING TASK 1")
delay(1000)
Log.d(TAG, "ENDING TASK 1")
}
suspend fun task2() {
Log.d(TAG, "STARTING TASK 2")
delay(2000)
Log.d(TAG, "ENDING TASK 2")
}
| Line | Timestamp (Seconds) | Log Message | Duration of delay() | Conclusion |
|---|---|---|---|---|
| 1 | 28.227 | STARTING TASK 1 | 1000ms (1 sec) | Task 1 starts. |
| 2 | 28.235 | STARTING TASK 2 | 2000ms (2 sec) | Immediately after Task 1 starts, Task 2 starts. This shows the two launch calls do not wait for each other. |
| 3 | 29.235 | ENDING TASK 1 | Logged exactly 1 second after Task 1 started (28.227 + ~1.000 = 29.227). | |
| 4 | 30.243 | ENDING TASK 2 | Logged exactly 2 seconds after Task 2 started (28.235 + ~2.000 = 30.235). |