最便宜网站建设,商务网站建设ppt,少儿免费学编程的网站,开发一个交友app多少钱前情提要
GlobalScope.launch(Dispatchers.Main) { // 默认是Default异步 // 1.从当前协程体作用域Dispatchers.Main 协程依附的线程 到 挂起点 挂起函数 到 执行 请求耗时操作 而 切换到 IO异步线程 // 2.IO异步线程执行完成后#xff0c;开始恢复#xff0c;当前作…前情提要
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 Continuationin T {public val context: CoroutineContext相当于 responseSuccess 结果↓ ↓public fun resumeWith(result: ResultT) 请求回调成功public inline fun T ContinuationT.resumeWithException(exception: Throwable): Unit resumeWith(Result.failure(exception)) 请求回调错误
}
suspend起到提醒的作用经此而已。suspend里面没有异步切换。就是假的挂起。 suspend必须有suspend调用 相当于有一个隐式的 Continuation 传到下一个函数