使用Kotlin协程配合Retrofit发送请求
Retrofit2.6开始增加了对Kotlin协程的支持,可以通过suspend函数进行异步调用。本文简单介绍一下使用Kotlin协程配合Retrofit使用,发起网络请求。
导入依赖#
app的build文件中加入:
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1'
- 注意依赖版本
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) {
// 失败逻辑
}
})
}
作者:sw-code
出处:https://www.cnblogs.com/sw-code/p/14451921.html
版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
未经作者同意,请勿转载;若经同意转载,请在文章明显位置注明作者和出处。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发中对象命名的一点思考
· .NET Core内存结构体系(Windows环境)底层原理浅谈
· C# 深度学习:对抗生成网络(GAN)训练头像生成模型
· .NET 适配 HarmonyOS 进展
· .NET 进程 stackoverflow异常后,还可以接收 TCP 连接请求吗?
· 本地部署 DeepSeek:小白也能轻松搞定!
· 如何给本地部署的DeepSeek投喂数据,让他更懂你
· 在缓慢中沉淀,在挑战中重生!2024个人总结!
· 从 Windows Forms 到微服务的经验教训
· 李飞飞的50美金比肩DeepSeek把CEO忽悠瘸了,倒霉的却是程序员