首發(fā)于公眾號: DSGtalk1989
33.協(xié)程 & Retrofit
本質(zhì)上來說,所有的Rxjava的情況我們都可以通過協(xié)程來實(shí)現(xiàn),這邊以利用最廣泛的網(wǎng)絡(luò)請求為例
首先添加相關(guān)依賴
implementation 'com.jakewharton.retrofit:retrofit2-kotlin-coroutines-adapter:0.9.2'
接口定義為如下,返回類型為Deferred
@GET("newsflash")
fun getWeatherDataByCoroutine(
@Query("per_page") per_page: Int
): Deferred<Response<KrResponse>>
添加callAdapter
.addCallAdapterFactory(CoroutineCallAdapterFactory())
最終調(diào)用,起全局協(xié)程,并通過await
方法實(shí)現(xiàn)同步請求
GlobalScope.launch {
try {
Log.e(
"xxxx",
"data : ${serviceManager.weatherService.getWeatherDataByCoroutine(3).await().body()!!.data.items[0]}"
)
} catch (e: Exception) {
Log.e("xxxxx", "e : ${e.message}")
}
}
Kotlin學(xué)習(xí)筆記之 1 基礎(chǔ)語法
Kotlin學(xué)習(xí)筆記之 2 基本數(shù)據(jù)類型
Kotlin學(xué)習(xí)筆記之 4 循環(huán)控制
Kotlin學(xué)習(xí)筆記之 8 擴(kuò)展
Kotlin學(xué)習(xí)筆記之 9 數(shù)據(jù)類與密封類
Kotlin學(xué)習(xí)筆記之 12 對象表達(dá)式和對象聲明
Kotlin學(xué)習(xí)筆記之 13 基礎(chǔ)操作符run、with、let、also、apply
Kotlin學(xué)習(xí)筆記之 14 包與導(dǎo)入
Kotlin學(xué)習(xí)筆記之 18 函數(shù)
Kotlin學(xué)習(xí)筆記之 19 高階函數(shù)與 lambda 表達(dá)式
Kotlin學(xué)習(xí)筆記之 20 內(nèi)聯(lián)函數(shù)
Kotlin學(xué)習(xí)筆記之 21 解構(gòu)聲明
Kotlin學(xué)習(xí)筆記之 28 協(xié)程基礎(chǔ)
Kotlin學(xué)習(xí)筆記之 29 上下文與調(diào)度器
Kotlin學(xué)習(xí)筆記之 30 協(xié)程取消與超時(shí)
Kotlin學(xué)習(xí)筆記之 31 協(xié)程掛起函數(shù)的組合