kotlin + retrofit + 協(xié)程 + ViewModel + LiveData 實現(xiàn) MVVM 框架,顯示網(wǎng)絡(luò)請求返回結(jié)果

本文僅為簡單demo,最后顯示結(jié)果如下:


image.png

使用Jetpack的框架一般如下

MVVM

LiveData 和 ViewModel一般結(jié)合起來使用。
LiveData:基于生命周期的消息訂閱
ViewModel:數(shù)據(jù)共享
本篇忽略Repository,和異常處理,僅涉及Activity + ViewModel + LiveData + Retrofit。
本篇架構(gòu)主要參考這篇,但有刪減。
Jetpack第五篇:實戰(zhàn)Retrofit+協(xié)程+LiveData+ViewMode寫一個簡單的網(wǎng)絡(luò)請求組件

1.添加依賴,開啟viewBinding 。

plugins {
    id 'com.android.application'
    id 'org.jetbrains.kotlin.android'
}

android {
    namespace 'com.example.retrofit'
    compileSdk 32

    defaultConfig {
        applicationId "com.example.retrofit"
        minSdk 21
        targetSdk 32
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
    viewBinding {
        enabled = true
    }
}

dependencies {

    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.5.1'
    implementation 'com.google.android.material:material:1.6.1'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'

    /*添加retrofit依賴庫*/
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'

    // liveData
    implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.4.0'

    // ViewModel
    implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.4.0'

}

2.manifest中添加網(wǎng)絡(luò)權(quán)限

    <uses-permission android:name="android.permission.INTERNET"/>

3.修改xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="30dp"
        android:background="@color/teal_200"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/getRandomCommentButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="隨機(jī)獲取評論"
        app:layout_constraintBottom_toBottomOf="@+id/getRandomMusicButton"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toEndOf="@+id/getRandomMusicButton"
        app:layout_constraintTop_toTopOf="@+id/getRandomMusicButton"
        app:layout_constraintVertical_bias="0.0" />

    <Button
        android:id="@+id/getRandomMusicButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="隨機(jī)獲取歌曲"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/getRandomCommentButton"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintHorizontal_chainStyle="spread"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.023" />

</androidx.constraintlayout.widget.ConstraintLayout>

4.創(chuàng)建接受服務(wù)器返回數(shù)據(jù)的類
在正式的請求網(wǎng)絡(luò)數(shù)據(jù)中,返回的數(shù)據(jù)的外嵌套部分都是一樣的,攜帶狀態(tài)碼、狀態(tài)信息、實體數(shù)據(jù)一起返回,我們可以將它封裝一個統(tǒng)一的數(shù)據(jù)回調(diào)類。

get的請求地址為:
https://api.uomg.com/api/rand.music?sort=熱歌榜&format=json

post請求鏈接:
https://api.uomg.com/api/comments.163?format=JSON

get請求之后,使用在線代碼格式化 https://tool.oschina.net/codeformat/json

請求之后,返回數(shù)據(jù)如下:

返回的數(shù)據(jù)如下
{
    "code": 1,
    "data": {
        "name": "你還好嗎",
        "url": "http://music.163.com/song/media/outer/url?id=1985080502",
        "picurl": "http://p3.music.126.net/Hr54Q0qzquMfp3xVLOnMQw==/109951167914933261.jpg",
        "artistsname": "陳鈺羲"
    }
}
返回參數(shù)說明:
名稱  類型  說明
    code    string  返回的狀態(tài)碼
    data    string  返回歌曲數(shù)據(jù)
    msg string  返回錯誤提示信息!

因此需要一個類,存放這個結(jié)果。
新建一個ResponseResult如下所示。

class ResponseResult<T>(val code:Int, val msg: String, val data: T?)

而data中的數(shù)據(jù),需要JavaBean類去存放這些數(shù)據(jù)。
可直接新建一個kotlin file:DataBean.kt,在其中定義data 數(shù)據(jù)類:RandomMusicDataBean 和 RandomCommentDataBean 。



//網(wǎng)易云音樂隨機(jī)歌曲  https://api.uomg.com/doc-rand.music.html
/*
https://api.uomg.com/api/rand.music?sort=熱歌榜&format=json
定義的參數(shù)名要與返回的數(shù)據(jù)命名一致,否則解析失敗
    "data": {
        "name": "你還好嗎",
        "url": "http://music.163.com/song/media/outer/url?id=1985080502",
        "picurl": "http://p3.music.126.net/Hr54Q0qzquMfp3xVLOnMQw==/109951167914933261.jpg",
        "artistsname": "陳鈺羲"
    }
* */
data class RandomMusicDataBean(
    val name: String,
    val url: String,
    val picurl: String,
    val artistsname: String)

//網(wǎng)易云音樂熱門評論 https://api.uomg.com/doc-comments.163.html
/*
https://api.uomg.com/api/comments.163?format=JSON
{
    "code": 1,
    "data": {
        "name": "可樂",
        "url": "http://music.163.com/song/media/outer/url?id=29759733.mp3",
        "picurl": "http://p4.music.126.net/qOfVT6izV4mBe4IyQn489Q==/18190320370401891.jpg",
        "artistsname": "趙紫驊",
        "avatarurl": "http://p4.music.126.net/b4fKe5gUrqD1rJzG5EZUbQ==/109951163130998723.jpg",
        "nickname": "陳可樂cola",
        "content": "兒子問父親結(jié)婚是什么感受 ,   父親說就是把你手機(jī)里所有的音樂都刪掉,只留下最喜歡的一首,然后無限循環(huán),由喜歡到厭倦再到習(xí)慣"
    }
}
*
* */
data class RandomCommentDataBean(
    val name: String,
    val url: String,
    val picurl: String,
    val artistsname: String,
    val nickname: String,
    val content: String)


5.創(chuàng)建用于描述網(wǎng)絡(luò)接口的類: Api。
用suspend修飾,返回值沒有Call。

interface Api {
    //Url的組成,retrofit把網(wǎng)絡(luò)請求的Url分成兩部分設(shè)置:
    //第一部分在創(chuàng)建Retrofit實例時通過.baseUrl()設(shè)置,
    //第二部分在接口注解中設(shè)置
    // 網(wǎng)絡(luò)請求的完整地址Url = Retrofit實例.baseUrl()+網(wǎng)絡(luò)請求接口注解()
    // baseUrl : https://api.uomg.com/

    //https://api.uomg.com/api/rand.music?sort=熱歌榜&format=json
    // 協(xié)程 get 請求 需加suspend 返回值去掉call
    @GET("api/rand.music")
    suspend fun getRandomMusicByCoroutine(
        @Query("sort") sort: String,
        @Query("format") format: String
    ): ResponseResult<RandomMusicDataBean>

    // https://api.uomg.com/api/comments.163?format=text
    // 協(xié)程 post 請求 需加suspend 返回值去掉call
    @FormUrlEncoded
    @POST("api/comments.163")
    suspend fun getRandomCommentByCoroutine(
        @Field("format")format: String
    ):ResponseResult<RandomCommentDataBean>

}

6.在ViewModel中使用LiveData 和 Retrofit。
kotlin中要盡量用val。
新建RandomViewModel.kt,繼承ViewModel,在RandomViewModel中使用LiveData 和 Retrofit。

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

class RandomViewModel: ViewModel() {

    private val retrofit: Retrofit by lazy {
        Retrofit.Builder()
            //設(shè)置網(wǎng)絡(luò)請求BaseUrl地址
            .baseUrl("https://api.uomg.com/")
            //設(shè)置數(shù)據(jù)解析器
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    }

    var randomMusicLiveData: MutableLiveData<RandomMusicDataBean> = MutableLiveData()

    var randomCommentLiveData: MutableLiveData<RandomCommentDataBean> = MutableLiveData()

    fun getRandomMusicData(){
        //  viewmodel-ktx 庫中l(wèi)aunch開啟協(xié)程 獲取數(shù)據(jù) retrofit2.6 版本及以上 支持
        viewModelScope.launch {
            try {
                val response = getRandomMusicByCoroutine()
                randomMusicLiveData.postValue(response.data!!)
            }catch (e : Exception){
                e.printStackTrace()
            }

        }
    }

    fun getRandomCommentData(){
        viewModelScope.launch {
            try {
                val response = getRandomCommentByCoroutine()
                randomCommentLiveData.postValue(response.data!!)
            }catch (e : Exception){
                e.printStackTrace()
            }

        }
    }

    // 處理耗時任務(wù) 網(wǎng)絡(luò)請求
    private suspend fun getRandomMusicByCoroutine():ResponseResult<RandomMusicDataBean>{
        return withContext(Dispatchers.Default){
            val api: Api = retrofit.create<Api>(Api::class.java)
            // withContext  默認(rèn)返回最后一行
            api.getRandomMusicByCoroutine("新歌榜", "json")
        }
    }

    private suspend fun getRandomCommentByCoroutine():ResponseResult<RandomCommentDataBean>{
        return withContext(Dispatchers.Default){
            val api: Api = retrofit.create<Api>(Api::class.java)
            api.getRandomCommentByCoroutine("JSON")
        }
    }

}

AndroidX lifecycle v2.1.0在 ViewModel 類中引入了擴(kuò)展屬性viewModelScope,直接使用即可。

關(guān)于協(xié)程的理解,可參考這篇:
Kotlin Jetpack 實戰(zhàn) | 09. 圖解協(xié)程原理

7.Activity中使用。
通過LiveData.observe注冊觀察者并監(jiān)聽數(shù)據(jù)變化。

const val TAG = "MainActivity"
class MainActivity : AppCompatActivity() {

    private val randomViewModel by lazy {
        ViewModelProvider(this).get(RandomViewModel::class.java)
    }

    private val binDing by lazy {
        ActivityMainBinding.inflate(layoutInflater)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //setContentView(R.layout.activity_main)
        setContentView(binDing.root)

        startObserver()

        binDing.getRandomMusicButton.setOnClickListener {
            randomViewModel.getRandomMusicData()

        }

        binDing.getRandomCommentButton.setOnClickListener {
            randomViewModel.getRandomCommentData()

        }
    }

    private fun startObserver() {
        randomViewModel.randomMusicLiveData.observe(this)  {
            binDing.textView.text =
                it.run {
                    """返回的數(shù)據(jù):
name : $name
url : $url
picurl : $picurl
artistsname : $artistsname
"""
                }
        }


        randomViewModel.randomCommentLiveData.observe(this) {
            binDing.textView.text =
                it.run {
"""返回的數(shù)據(jù):
name : $name
url : $url
picurl : $picurl
artistsname : $artistsname
nickname : $nickname
content : $content
"""
            }
        }
        
    }

}

運行結(jié)果如下所示


image.png

project下只有5個類,而且代碼量很少,編譯器會自動生成大量代碼(例如data數(shù)據(jù)類,suspend修飾的函數(shù))。


image.png

使用協(xié)程的話,就不用寫回調(diào)了,如果不使用協(xié)程,只使用retrofit的話,就需要寫回調(diào),用suspend修飾,會執(zhí)行CPS 轉(zhuǎn)換,就是將原本的同步掛起函數(shù)轉(zhuǎn)換成CallBack 異步代碼的過程。這個轉(zhuǎn)換是編譯器在背后做的。

fun  getRandomMusicData(){
        //創(chuàng)建網(wǎng)絡(luò)請求接口對象實例
        val api: Api = retrofit.create<Api>(Api::class.java)
        //對發(fā)送請求進(jìn)行封裝,傳入接口參數(shù)
        val randomMusicCall: Call<ResponseResult<RandomMusicDataBean>> =
            api.getRandomMusic("新歌榜", "json")

        //發(fā)送網(wǎng)絡(luò)請求(異步)
        Log.e(TAG, "get == url:" + randomMusicCall.request().url())
        // object定義的匿名內(nèi)部類
        randomMusicCall.enqueue(object: Callback<ResponseResult<RandomMusicDataBean>> {
            override fun onResponse(
                call: Call<ResponseResult<RandomMusicDataBean>>,
                response: Response<ResponseResult<RandomMusicDataBean>>
            ) {
                randomMusicLiveData.postValue(response.body()?.data!!)

            }

            override fun onFailure(call: Call<ResponseResult<RandomMusicDataBean>>, t: Throwable) {

            }

        })

    }

參考鏈接:
Retrofit2 詳解和使用(一)
Retrofit2 實戰(zhàn)(一、使用詳解篇)
在線代碼格式化
Jetpack第五篇:實戰(zhàn)Retrofit+協(xié)程+LiveData+ViewMode寫一個簡單的網(wǎng)絡(luò)請求組件

LiveData與ViewModel基礎(chǔ)使用篇
重學(xué)Android Jetpack(七)之— LiveData & ViewModel
ViewModel中的簡易協(xié)程:viewModelScope
Kotlin中的協(xié)程在Android端的使用

官方文檔:
LiveData 概覽

?著作權(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)容