Retrofit2.6開始增加了對Kotlin協程的支持,可以通過suspend函數進行異步調用。本文簡單介紹一下Retrofit中協程的使用
導入依賴
app的build文件中加入:
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
- 注意依賴版本
data class
data class ResultData<T>(
val code: Int,
val message: String,
val data: T
)
Retrofit實例
/**
* 創建Retrofit提供API Service
*/
object RetrofitClient {
const val BASE_URL = "http://192.168.2.194:8080/" // http://localhost:8080/
val okHttpClient = OkHttpClient.Builder()
.callTimeout(30, TimeUnit.SECONDS)
.build()
val retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClient)
.build()
val articleService = retrofit.create(ArticleService::class.java)
}
Service
interface ArticleService {
@GET("article/get/{id}")
suspend fun getArticleById(@Path("id") id: Long): ResultData<Article>
}
- 注意,請求路徑前不加
/
,因為BASE_URL
中已經加了
在ViewModel中使用
class ArticleViewModel : ViewModel() {
val article by lazy {
MutableLiveData<Article>()
}
fun getArticle(id: Long) {
viewModelScope.launch {
val article = RetrofitClient.articleService.getArticleById(id)
contentList.value = articleList.data
Log.d("ViewPagerViewModel", "getArticle: $article")
}
}
}
ViewModelScope
為了調用suspend方法,需要提供一個CoroutineScope,如果實在ViewModel中進行api請求,可以像實例中那樣使用ktx提供的viewModelScope,viewModelScope可以幫助我們在viewModel的onCleared時自動進行job的cancel,否則需要在手動cancel。
不在ViewModel中使用,例如在Activity中使用時,可以如下調用
CoroutineScope(Dispatchers.Main).launch {
// ...
}
不使用協程
Service
interface ArticleService {
@GET("article/get/{id}")
fun getArticleById(@Path("id") id: Long): Call<Article>
}
返回Call類型結果,通過enqueue插入隊列等待回調處理
fun getArticle(id: Long) {
private val api = RetrofitClient.articleService
api.getArticleById().enqueue(object : Callback<Article> {
override fun onResponse(call: Call<Article>, response: Response<Article>) {
// 成功邏輯
}
override fun onFailure(call: Call<Article>, t: Throwable) {
// 失敗邏輯
}
})
}