前言
最近一直在修炼Kotlin,说实话真香真好用,刚好公司准备交给我一个新项目,于是打算直接用Kotlin来构建项目。刚好整体架构搭建完毕了,于是把网络请求这一部分先分享给大家。这次使用到的是 协程+ retrofit +mvvm的模式,我这儿直接用一个简单的demo来看一下具体的实现方式吧。文章只是描述实现思路,需要demo的直接跳到文末。
项目配置
首先先引入所需要的依赖
implementation 'android.arch.lifecycle:extensions:1.1.1'
//协程
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.1.1'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.1.1'
//retrofit + okHttp3
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
implementation 'com.jakewharton.retrofit:retrofit2-kotlin-coroutines-adapter:0.9.2'
实现思路
不管设计模式这些,先来一个简单的网络请求,就retrofit的基本实现,看看需要哪些步骤
1.创建retrofit
~~~
val retrofit = Retrofit.Builder()
.baseUrl(RetrofitClient.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(CoroutineCallAdapterFactory())
.build()
~~~
2.创建service接口
~~~
interface RequestService {
@GET("wxarticle/chapters/json")
fun getDatas() : Call<DataBean>
}
~~~
3.发起请求
~~~
val service = retrofit.create(RequestService::class.java)
service.getDatas().enqueue(object : Callback<DataBean> {
override fun onFailure(call: retrofit2.Call<DataBean>, t: Throwable) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun onResponse(call