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鏈接就會不讓發,就很頭大。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。