最近我司大佬們在項目中引入了協(xié)程,之前已經(jīng)和大家介紹過協(xié)程了,不清楚的同學(xué)可以看一下之前的文章。
今天和大家介紹一個協(xié)程的小技巧,Retrofit自 2.6 版本后,原生支持協(xié)程,所以使用 協(xié)程 + Retrofit 可以縮減我們的代碼,加速我們的應(yīng)用開發(fā)。

雖然,很多大佬們都已經(jīng)十分熟悉這個技巧,萬一有同學(xué)不熟悉呢?
目標(biāo)
簡單起見,我們使用 Github 官方的 Api,查詢官方返回的倉庫列表。
如果你學(xué)習(xí)過官方 Paging Demo 的源碼,會發(fā)現(xiàn)這份代碼很熟悉,因為這份代碼很大一部分來自這個Demo。
一、引入依賴
協(xié)程和 Retrofit 的版本:
dependencies {
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.4.2'
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.4.2"
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
implementation 'com.squareup.okhttp3:logging-interceptor:4.0.0'
}
二、使用Retrofit
創(chuàng)建一個 interface:
interface GithubApi {
@GET("search/repositories?sort=stars")
suspend fun searchRepos(
@Query("q") query: String,
@Query("page") page: Int,
@Query("per_page") itemsPerPage: Int
): RepoSearchResponse
}
和我們平時使用 Retrofit 有兩點不一樣:
- 需要在函數(shù)前加上
suspend修飾符 - 直接使用我們需要返回的類型,不需要包上
Call<T>或者Observable<T>
RepoSearchResponse 是返回的數(shù)據(jù):
data class RepoSearchResponse(
@SerializedName("total_count") val total: Int = 0,
@SerializedName("items") val items: List<Repo> = emptyList()
)
data class Repo(
@SerializedName("id") val id: Long,
@SerializedName("name") val name: String,
@SerializedName("full_name") val fullName: String,
@SerializedName("description") val description: String?,
@SerializedName("html_url") val url: String,
@SerializedName("stargazers_count") val stars: Int,
@SerializedName("forks_count") val forks: Int,
@SerializedName("language") val language: String?
)
之后的步驟就和我們平常使用 Retrofit 一致:
- 創(chuàng)建一個
OkHttpClient - 創(chuàng)建一個
Retrofit - 返回上面創(chuàng)建的接口
代碼:
interface GithubApi {
//... 代碼省略
companion object {
private const val BASE_URL = "https://api.github.com/"
fun createGithubApi(): GithubApi {
val logger = HttpLoggingInterceptor()
logger.level = HttpLoggingInterceptor.Level.BASIC
val client = OkHttpClient.Builder()
.addInterceptor(logger)
.sslSocketFactory(SSLSocketClient.getSSLSocketFactory(),
object : X509TrustManager {
override fun checkClientTrusted(
chain: Array<X509Certificate>,
authType: String
) {}
override fun checkServerTrusted(
chain: Array<X509Certificate>,
authType: String
) {}
override fun getAcceptedIssuers(): Array<X509Certificate> {
return arrayOf()
}
})
.hostnameVerifier(SSLSocketClient.getHostnameVerifier())
.build()
return Retrofit.Builder()
.baseUrl(BASE_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(GithubApi::class.java)
}
}
}
因為接口是 Https 請求,所以需要加上忽略 SSL 的驗證,其他都一樣了。
三、使用協(xié)程去請求
初始化 RecyclerView 的代碼就不放了,比較簡單:
class MainActivity : AppCompatActivity() {
val scope = MainScope()
private val mAdapter by lazy {
MainAdapter()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// ... 初始化RecyclerView
fetchData()
}
private fun fetchData(){
scope.launch {
try {
val result = GithubApi.createGithubApi().searchRepos("Android", 0, 20)
if(result != null && !result.items.isNullOrEmpty()){
mAdapter.submitList(result.items)
}
}catch (e: Exception){
e.printStackTrace()
}
}
}
override fun onDestroy() {
super.onDestroy()
scope.cancel()
}
}
協(xié)程中最方便的還是省去切線程的步驟,用同步代碼處理耗時的異步網(wǎng)絡(luò)請求。
需要注意的是,由于沒有使用 Lifecycle 的 KTX 的擴展庫,所以協(xié)程作用域的生命周期得我們自己去釋放,在上面的代碼中,我是在 onCreate 方法中啟動了一個協(xié)程,然后在 onDestroy 方法中去取消了正在執(zhí)行的任務(wù),以防內(nèi)存泄漏。
總結(jié)
協(xié)程 + Retrofit 的方便之處在于:使用同步代碼處理異步的網(wǎng)絡(luò)請求,減去 Retrofit 中網(wǎng)絡(luò)回調(diào)或者 RxJava + Retrofit 的請求回調(diào)。
精彩內(nèi)容
如果覺得本文不錯,「點贊」是對作者最大的鼓勵~
技術(shù)不止,文章有料,關(guān)注公眾號 九心說,每周一篇高質(zhì)好文,和九心在大廠路上肩并肩。