FAQ
問:Retrofit流程僚害?
答:(1)Retrofit.Builder填充初始化參數(shù)--->
(2) builder.build()? 創(chuàng)建callbackExecutor (主線程切換),并new Retrofit()---->
(3)retrofit.create() 使用動態(tài)代理繁调,解析注解萨蚕,拼接參數(shù)
(4)call.enqueue()發(fā)起請求,調用RealCall.enqueue()? 將請求交給okhttp
(5)AsyncCall 的execute()? 蹄胰,getResponseWithInterceptorChain()開啟責任鏈岳遥,發(fā)起請求,獲取響應結果
(6)responseCallback.onResponse 回調給okhttp結果(此時處于子線程)
(7)callbackExecutor.execute 將數(shù)據(jù)切回主線程裕寨。
問:Retrofit是如何進行線程切換的寒随?
答:(1)首先,在builder.build()方法創(chuàng)建retrofit對象時,會初始化一個主線程callbackExecutor妻往。
(2)在enqueue方法中,使用線程池創(chuàng)建執(zhí)行子線程试和,真正的請求發(fā)生在realCall的 execute方法中讯泣,這樣,就將線程切換到了子線程阅悍。
(3)通過okhttp請求結束好渠,在okhttp的onResponse方法中,使用executorCallback將數(shù)據(jù)拋回主線程节视。
問:callbackExecutor切回主線程的方式拳锚?
答:它的原理是獲取一個主線程的looper,然后寻行,通過post方法霍掺,將數(shù)據(jù)切回主線程。