這篇是一個(gè)簡(jiǎn)單的實(shí)戰(zhàn),用前面的學(xué)到的東西寫一個(gè)簡(jiǎn)單的網(wǎng)絡(luò)請(qǐng)求框架。
如果對(duì)LiveData,ViewMode等不太了解的可以看下:
Jetpack第二篇:Lifecycles - 簡(jiǎn)書 (jianshu.com)
Jetpack第三篇:LiveData - 簡(jiǎn)書 (jianshu.com)
Jetpack第四篇:ViewModel - 簡(jiǎn)書 (jianshu.com)
這篇文章就用Retrofit+協(xié)程+LiveData+ViewMode搭建一個(gè)網(wǎng)絡(luò)請(qǐng)求組件。
這個(gè)是最簡(jiǎn)單的一個(gè)demo,可以在這個(gè)基礎(chǔ)上適當(dāng)?shù)倪M(jìn)行封裝來(lái)。
1、主要內(nèi)容
- 導(dǎo)入依賴
- RetrofitManger:主要用于Retrofit初始化
- LiveData:數(shù)據(jù)分發(fā)
- ViewModel:數(shù)據(jù)獲取(使用ViewModel協(xié)程的拓展函數(shù))
2、導(dǎo)入依賴
注意:我這邊使用的依賴都是當(dāng)時(shí)最新,并不是現(xiàn)在最新。
// kotlin (我這里用的是Kotlin語(yǔ)言)
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'
// 協(xié)程
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.4"
// 網(wǎng)絡(luò)請(qǐng)求
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、網(wǎng)絡(luò)請(qǐng)求相關(guān)
RetrofitManger 我們使用retrofit2.9.0的版本,retrofit2.6.0版本就可以使用suspend關(guān)鍵字能和攜程比較好的組合使用。RetrofitManger中初始化了Retrofit、Okhttp等等一些配置,我這邊的Api接口使用的是單例模式防止整個(gè)應(yīng)用中產(chǎn)生大量的Retrofit對(duì)象,保證只有一個(gè)Api對(duì)象的產(chǎn)生。
我這里用的接口是: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標(biāo)記的方法,標(biāo)記這個(gè)是一個(gè)攜程使用的異步方法。
interface AppApi {
// 和協(xié)程聯(lián)用
@GET("article/list/{page}/json")
suspend fun getArticleList(@Path("page") page: Int): Response<ArticleListBean>
}
4、封裝ViewModel
在ViewModel中封裝了獲取數(shù)據(jù)的方法,和LiveData。LiveData用于觀察數(shù)據(jù)的變化,當(dāng)獲取到數(shù)據(jù)時(shí),使用postValue將數(shù)據(jù)分發(fā)給Activity。
同時(shí)封裝了異常處理的方法:
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
這個(gè)是ViewModel的拓展方法,攜程自己也提供了Launch方法,但是建議用ViewModel提供的方法,因?yàn)檫@個(gè)地方有個(gè)注釋This scope will be canceled when ViewModel will be cleared
這個(gè)意思是當(dāng)ViewModel被銷毀時(shí),這個(gè)攜程會(huì)自己取消。
/**
* [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數(shù)據(jù)展示
初始化ViewModel,接收l(shuí)ivedata分發(fā)的數(shù)據(jù)。
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 {
})
}
}
運(yùn)行結(jié)果:
6、最后總結(jié)
以上的封裝思路如果對(duì)LiveData、ViewModel、攜程、Retrofit有一定理解的同學(xué),看起來(lái)確實(shí)覺(jué)得思路清晰,簡(jiǎn)單明了。所以如果想比較好的理解這套封裝,需要先把LiveData、ViewModel、攜程、Retrofit這幾個(gè)組件先去有簡(jiǎn)單的了解。
源碼:源碼是有的的,好像簡(jiǎn)書一貼github鏈接就會(huì)不讓發(fā),就很頭大。