Kotlin Coroutine(协程): 四、+ Retrofit

本文介绍了如何在Kotlin中利用Retrofit 2.6.0及以上版本结合Coroutines进行网络请求,通过创建DSL和扩展函数实现优雅的错误处理和响应代码。首先,展示了基本的Retrofit配置,包括设置协程支持、统一的响应实体和API接口。接着,通过RetrofitDSL类和协程扩展函数封装了请求过程,简化了在Activity和ViewModel中的使用。这种方式使得代码更简洁,异常处理更直观。


前言

Retrofit 从 2.6.0 版本开始, 内置了对 Kotlin Coroutines 的支持. 我们统一处理异常及响应状态码, 使用DSL 让代码更加漂亮整洁

先导包:

//协程
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.4.3"
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.4.3'

// Retrofit
implementation "com.squareup.retrofit2:retrofit:2.9.0"
implementation "com.squareup.retrofit2:converter-gson:2.9.0"
implementation "com.squareup.okhttp3:logging-interceptor:4.2.0"

一、准备工作

1.BaseResp

统一的返回实体, 包含 code, msg, data; 这种服务器响应结构比较常见

data class BaseResp<T>(
    // 响应状态码
    var code: Int = -1,
    // 响应信息
    var msg: String = "",
    // 数据实体
    var data: T? = null
)

2.Api

这里是一个验证码请求接口, 使用的 Json 提交参数

interface Api {
   
   
    @POST("api/getCode")
    suspend fun getCode(@Body body: RequestBody): BaseResp<JsonObject?>
}

3.ApiManager

使用 枚举单例模式; 包括 初始化 Retrofit, OkHttpClient, 添加请求Token, 请求日志打印.

/**
 * Retrofit 管理类;
 */
enum class ApiManager {
   
   
    INSTANCE;
    private val retrofit: Retrofit
    val mApi: Api
    private val mMediaTypeJson: MediaType?

    init {
   
   
        retrofit = Retrofit.Builder()
            .baseUrl("https://... 服务器地址")
            .client(initOkhttpClient())
            .addConverterFactory(GsonConverterFactory.create())
            .build()
        mApi = retrofit.create(Api::class.java)
        mMediaTypeJson = "application/json; charset=utf-8".toMediaTypeOrNull()
    }

    private fun initOkhttpClient(): OkHttpClient {
   
   
        return OkHttpClient.Build
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值