Kotlin (5): Coroutines

學習Kotlin最重要的項目,就是Coroutines. 這可是之前Java所沒有的,Java的Thread 不好用,這個coroutines才是適合非同步領域的東西. Coroutines 這個單字是由兩個英文單字合併而成的,分別是 cooperation + routine.用來做非同步和非阻塞任務.意思就是要各個子任務程協作運行的意思,所以明白了它被創造出來是要解決異步問題的。 Kotlin的協程完美復刻了Go語言的協程設計模式( 作用域/channel/select), 將作用域用對象分類; 可以更好地控制作用域生命週期; await模式(類似JavaScript的異步任務解決方案) Kotlin參考RxJava響應式框架創造出Flow 使用協程開始就不需要考慮線程的問題, 只需要在不同場景使用不同的調度器就好 github: https://github.com/Kotlin/kotlinx.coroutines kotlin home: https://kotlinlang.org reference: https://juejin.cn/post/6987724340775108622 仔細看完文件後,發現coroutines並不是那麼簡單,反而使用方法有點複雜. ---- dependencies { implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:+' implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:+' } ----- coroutine 典型用法, 啟動協程: 啟動一個新的協程, 常用的主要有以下幾種方式:它們被稱為coroutine builders. launch async (可從Coroutine 返回值) runBlocking ---- launch– Launches new coroutine without blocking current thread and returns a reference to the coroutine as a Job. The coroutine is canceled when the resu