協(xié)程+Retrofit 讓你的代碼足夠優(yōu)雅

最近我司大佬們在項目中引入了協(xié)程,之前已經(jīng)和大家介紹過協(xié)程了,不清楚的同學(xué)可以看一下之前的文章。

《抽絲剝繭Kotlin - 協(xié)程》

今天和大家介紹一個協(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 有兩點不一樣:

  1. 需要在函數(shù)前加上 suspend 修飾符
  2. 直接使用我們需要返回的類型,不需要包上 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 一致:

  1. 創(chuàng)建一個 OkHttpClient
  2. 創(chuàng)建一個 Retrofit
  3. 返回上面創(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ò)請求。

需要注意的是,由于沒有使用 LifecycleKTX 的擴展庫,所以協(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ì)好文,和九心在大廠路上肩并肩。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容