前情提要
GlobalScope.launch(Dispatchers.Main) { // 默認是Default異步
??? // 1.從當前協程體作用域Dispatchers.Main 協程依附的線程 到 掛起點 掛起函數 到 執行 請求耗時操作 而 切換到 IO異步線程
??? // 2.IO異步線程執行完成后,開始恢復,當前作用域Dispatchers.Main,執行左邊代碼,保證了 左邊代碼恢復到 UI線程
?? var serverResponseInfo0 = requestLoadUser()}
private suspend fun requestLoadUser() : String {}// 上面函數 suspend關鍵字的原理,其實就是 ResponseCallBack// 把上面函數,反編譯成Java的代碼,是這個樣子,請看下面代碼:
/* ResponseCallBack == Continuation只不過這個Continuation換個名字而已,他就是 ResponseCallBackpublic static final Object requestLoadUser(Continuation $ completion) {
// Continuation 后面剩余代碼的恢復工作
Continuation--》繼續 持續
public interface Continuation<in T> {public val context: CoroutineContext相當于 responseSuccess 結果↓ ↓public fun resumeWith(result: Result<T>) 請求回調成功public inline fun <T> Continuation<T>.resumeWithException(exception: Throwable): Unit =resumeWith(Result.failure(exception)) 請求回調錯誤
}
suspend起到提醒的作用,經此而已。suspend里面沒有異步切換。就是假的掛起。
suspend必須有suspend調用 相當于有一個隱式的 Continuation 傳到下一個函數