Jetpack第五篇:實戰Retrofit+協程+LiveData+ViewMode寫一個簡單的網絡請求組件

這篇是一個簡單的實戰,用前面的學到的東西寫一個簡單的網絡請求框架。
如果對LiveData,ViewMode等不太了解的可以看下:
Jetpack第二篇:Lifecycles - 簡書 (jianshu.com)
Jetpack第三篇:LiveData - 簡書 (jianshu.com)
Jetpack第四篇:ViewModel - 簡書 (jianshu.com)

這篇文章就用Retrofit+協程+LiveData+ViewMode搭建一個網絡請求組件。
這個是最簡單的一個demo,可以在這個基礎上適當的進行封裝來。

1、主要內容

主要內容
  • 導入依賴
  • RetrofitManger:主要用于Retrofit初始化
  • LiveData:數據分發
  • ViewModel:數據獲取(使用ViewModel協程的拓展函數)

2、導入依賴

注意:我這邊使用的依賴都是當時最新,并不是現在最新。

    // kotlin (我這里用的是Kotlin語言)
    implementation 'androidx.core:core-ktx:1.3.2'
    implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.2.0'

    // lifecycle
    implementation 'androidx.lifecycle:lifecycle-common-java8:2.3.0-alpha01'

    // liveData
    implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.3.0-alpha01'

    // ViewModel
    implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.0-alpha01'

    // 協程
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.4"

    // 網絡請求
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:4.7.2'

3、網絡請求相關

RetrofitManger 我們使用retrofit2.9.0的版本,retrofit2.6.0版本就可以使用suspend關鍵字能和攜程比較好的組合使用。RetrofitManger中初始化了Retrofit、Okhttp等等一些配置,我這邊的Api接口使用的是單例模式防止整個應用中產生大量的Retrofit對象,保證只有一個Api對象的產生。

我這里用的接口是:wanAndroid的公開Api接口。

object RetrofitManger {

    var mApi: AppApi? = null

    private const val CONNECTION_TIME_OUT = 10L
    private const val READ_TIME_OUT = 10L

    var API_URL = "https://www.wanandroid.com"

    fun getApiService(): AppApi {
        if (mApi == null) {
            synchronized(this) {
                if (mApi == null) {
                    val okHttpClient =
                        buildOkHttpClient()
                    mApi =
                        buildRetrofit(
                            API_URL,
                            okHttpClient
                        ).create(AppApi::class.java)
                }
            }
        }
        return mApi!!
    }

    private fun buildOkHttpClient(): OkHttpClient.Builder {
        val logging = HttpLoggingInterceptor()
        logging.level = HttpLoggingInterceptor.Level.BODY
        return OkHttpClient.Builder()
            .addInterceptor(logging)
            .connectTimeout(CONNECTION_TIME_OUT, TimeUnit.SECONDS)
            .readTimeout(READ_TIME_OUT, TimeUnit.SECONDS)
            .proxy(Proxy.NO_PROXY)
    }

    private fun buildRetrofit(baseUrl: String, builder: OkHttpClient.Builder): Retrofit {
        val client = builder.build()

        return Retrofit.Builder()
            .baseUrl(baseUrl)
            .addConverterFactory(GsonConverterFactory.create())
            .client(client).build()
    }
}

Response:

class Response<T>(
    val data: T?,
    val info: Int,
    val msg: String
)

Api:
可以看到使用suspend標記的方法,標記這個是一個攜程使用的異步方法。

interface AppApi {

    // 和協程聯用
    @GET("article/list/{page}/json")
    suspend fun getArticleList(@Path("page") page: Int): Response<ArticleListBean>
}

4、封裝ViewModel

在ViewModel中封裝了獲取數據的方法,和LiveData。LiveData用于觀察數據的變化,當獲取到數據時,使用postValue將數據分發給Activity。
同時封裝了異常處理的方法:

class CoroutinesViewModel : ViewModel() {

    val api by lazy { RetrofitManger.getApiService() }
    var articlesLiveData: MutableLiveData<MutableList<ArticleBean>> = MutableLiveData()

    var apiError:MutableLiveData<Throwable> = MutableLiveData()

    fun getArticles(page: Int) {

        val exception = CoroutineExceptionHandler { coroutineContext, throwable ->
            apiError.postValue(throwable)
            Log.i("CoroutinesViewModel",throwable.message!!)
        }

        viewModelScope.launch(exception) {
            val respose = api.getArticleList(page)
            if (respose.info == 0) {
                articlesLiveData.postValue(respose.data?.datas)
            } else {
                articlesLiveData.postValue(mutableListOf())
            }
        }
    }

}

4.1、viewModelScope.launch

這個是ViewModel的拓展方法,攜程自己也提供了Launch方法,但是建議用ViewModel提供的方法,因為這個地方有個注釋This scope will be canceled when ViewModel will be cleared這個意思是當ViewModel被銷毀時,這個攜程會自己取消。

/**
 * [CoroutineScope] tied to this [ViewModel].
 * This scope will be canceled when ViewModel will be cleared, i.e [ViewModel.onCleared] is called
 *
 * This scope is bound to
 * [Dispatchers.Main.immediate][kotlinx.coroutines.MainCoroutineDispatcher.immediate]
 */
val ViewModel.viewModelScope: CoroutineScope
        get() {
            val scope: CoroutineScope? = this.getTag(JOB_KEY)
            if (scope != null) {
                return scope
            }
            return setTagIfAbsent(JOB_KEY,
                CloseableCoroutineScope(SupervisorJob() + Dispatchers.Main.immediate))
        }

internal class CloseableCoroutineScope(context: CoroutineContext) : Closeable, CoroutineScope {
    override val coroutineContext: CoroutineContext = context

    override fun close() {
        coroutineContext.cancel()
    }
}

5、Activity數據展示

初始化ViewModel,接收livedata分發的數據。

class MainActivity : AppCompatActivity() {

    private val viewModel by lazy { ViewModelProvider(this).get(CoroutinesViewModel::class.java) }

    private var textShowData:TextView? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initView()
        startObserver()
    }

    private fun initView() {
        val btnGetData = findViewById<Button>(R.id.btnGetData)
        btnGetData.setOnClickListener {
            viewModel.getArticles(1)
        }
        textShowData = findViewById<TextView>(R.id.tvInfo)
    }

    private fun startObserver() {
        viewModel.articlesLiveData.observe(this, Observer {
            it.run {
                if (this.size > 0) {
                    val text = StringBuilder()
                    this.forEach {
                        text.append(it.title+"\n")
                    }
                    textShowData?.text = text
                }
            }
        })

        viewModel.apiError.observe(this, Observer {

        })
    }
}

運行結果:


image.png

6、最后總結

以上的封裝思路如果對LiveData、ViewModel、攜程、Retrofit有一定理解的同學,看起來確實覺得思路清晰,簡單明了。所以如果想比較好的理解這套封裝,需要先把LiveData、ViewModel、攜程、Retrofit這幾個組件先去有簡單的了解。

源碼:源碼是有的的,好像簡書一貼github鏈接就會不讓發,就很頭大。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,967評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,273評論 3 415
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 175,870評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,742評論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,527評論 6 407
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,010評論 1 322
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,108評論 3 440
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,250評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,769評論 1 333
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,656評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,853評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,371評論 5 358
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,103評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,472評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,717評論 1 281
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,487評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,815評論 2 372