Kotlin 中的 suspend 函式
 
本文將介紹 Kotlin Coroutine 中的 suspend 函式以及如何實現它。
Kotlin 中的 suspend 函式
    
Kotlin Coroutine 中的幾乎所有內容都圍繞著 suspend 函式。協程就像輕量級執行緒,可以與程式的其餘部分同時執行一段程式碼。
協程不受任何特定執行緒的約束,因此我們可以將它們掛起在一個執行緒中並在另一個執行緒中恢復它們。suspend 功能可以在任何給定時間暫停和繼續。
它可以讓一個龐大的程式不間斷地執行和完成。
我們可以通過在宣告函式名稱前使用 suspend 關鍵字來定義 suspend 函式。但是要執行一個 suspend 函式,我們需要通過另一個 suspend 函式或從協程呼叫它;否則,它會丟擲一個錯誤。
儘管我們使用 suspend 關鍵字定義了 suspend 函式,但它在螢幕後面被編譯為標準函式。編譯後的函式採用附加引數 Continuation<T>。
程式碼:
suspend fun example(param: Int): Int {
    // another running operation
}
上面的程式碼變成了,
fun example(param: Int, callback: Continuation<Int>): Int {
    // another running operation
}
這是 suspend 函式的一個簡單示例:
import kotlinx.coroutines.*
fun main() = runBlocking {
    launch { suspendExample() }
    println("Hi")
}
suspend fun suspendExample() {
    delay(2000L)
    println("Welcome!")
}
輸出:

Kotlin 中的 suspend 函式示例
讓我們看一下 Kotlin 中的另一個掛起函式,以更好地瞭解併發執行緒如何一個接一個地執行。
在本例中,我們將使用 2 個延遲函式在螢幕上顯示不同的列印資訊。
import kotlinx.coroutines.*
fun main() = runBlocking {
    suspendExample()
    println("Programming")
}
suspend fun suspendExample() = coroutineScope {
    launch {
        delay(1000L)
        println("Kotlin")
    }
    launch {
        delay(500L)
        println("Welcome to")
    }
    println("Hello, ")
}
輸出:

Kailash Vaviya is a freelance writer who started writing in 2019 and has never stopped since then as he fell in love with it. He has a soft corner for technology and likes to read, learn, and write about it. His content is focused on providing information to help build a brand presence and gain engagement.
LinkedIn