跳到主內容

【Kotlin】coroutines

相關資源
官方文件:coroutines-guide

一. 什麼是coroutines?(協同程序)

(一)意義:
coroutines的中文翻譯為「協程」,「深入淺出kotlin」一書中形容協程就像「輕量的執行緒」(light-weight threads)。使用協同程序的意義就在於,啟動一個背景工作時,同時讓其他程式不需要等待工作完成就可以做別的事情,用戶體驗會比較好。(鄉民翻譯:使用者用起來快樂,客戶付錢就會乾脆

(二)優點:
1. 解決傳統執行緒的困擾:
影片及書本中都以「在main thread連接internet」為例,由於android明令禁止應用程式在主執行緒存取網路,因此,此時主執行緒會被阻塞。而傳統的執行序在主執行緒阻塞未被移除前,是不會再執行其他作業的,coroutines也是執行緒,只不過在這種情形會被暫停,但是不會阻塞父執行緒。

2. 很適合執行背景工作:
如(一)所述,使用協同程序的好處就在於,啟動一個背景工作時,同時讓其他程式不需要等待工作完成就可以做別的事情,用戶體驗會比較好。

 

fun main() = runBlocking { // this: CoroutineScope
    launch { // launch a new coroutine and continue
        delay(1000L) // non-blocking delay for 1 second (default time unit is ms)
        println("World!") // print after delay
    }
    println("Hello") // main coroutine continues while a previous one is delayed
}

// Hello
// World!