Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Briefly Introduction of Kotlin coroutines

Elvis Lin
October 19, 2018

Briefly Introduction of Kotlin coroutines

Introduce basic concepts of Kotlin coroutines

Elvis Lin

October 19, 2018
Tweet

More Decks by Elvis Lin

Other Decks in Programming

Transcript

  1. 關於我 • Elvis Lin • Android, iOS 與 React Native

    永遠的初學者 • Twitter: @elvismetaphor • Blog: https://blog.elvismetaphor.me #JCConf Taiwan 2018
  2. 循序處理理的程式與Thread fun main(args: Array<String>) {
 println("First")
 printDelayed(“Second")
 println("Third")
 } fun

    printDelayed(message: String) {
 Thread.sleep(1000)
 println(message)
 } #JCConf Taiwan 2018
  3. 循序處理理的程式與 Coroutines fun main(args: Array<String>) {
 println(“First")
 runBlocking {
 printDelay("Second")


    }
 println("Third")
 } suspend fun printDelay(message: String) {
 delay(1000)
 println(message)
 } #JCConf Taiwan 2018
  4. 循序處理理的程式
 與 Coroutines(簡易易版) fun main(args: Array<String>) {
 println(“First")
 runBlocking {


    delay(1000)
 println(“Second”)
 }
 println("Third")
 } #JCConf Taiwan 2018
  5. 並⾏行行處理理的程式與 Thread fun main(args: Array<String>) {
 println("First")
 printNonBlocking("Second")
 println("Third")
 }

    fun printNonBlocking(message: String) {
 Thread {
 Thread.sleep(1000)
 println(message)
 }.start()
 } // Output:
 First
 Third
 Second
  6. 並⾏行行處理理的程式與 coroutines fun main(args: Array<String>) {
 println("First")
 launch {
 printDelay("Second")


    }
 println("Three")
 } suspend fun printDelay(message: String) {
 delay(1000)
 println(message)
 } // Output:
 First
 Third
 Second #JCConf Taiwan 2018
  7. Coroutines • Coroutines are like very light-weight thread • Coroutines

    computations can be done without blocking other threads. • Coroutine 的執⾏行行可以更更有效地利利⽤用原本已經建立在 ThreadPool 裡⾯面的 Threads #JCConf Taiwan 2018
  8. suspend • ⼀一個 modifier • ⼀一個 suspend 的 function 只可以被

    suspend function 或另⼀一 個 coroutine 呼叫 #JCConf Taiwan 2018
  9. async & await • aysnc {…} 會回傳⼀一個 Deferred<T> • 在回傳的

    deferred 上⾯面加上 await 會獲得值 #JCConf Taiwan 2018 val value = async {calculate(1)}.await()