Retrofit集成Sandwich教程:从0到1实现响应状态管理

【免费下载链接】sandwich 🥪 Sandwich is an adaptable and lightweight sealed API library designed for handling API responses and exceptions in Kotlin for Retrofit, Ktor, and Kotlin Multiplatform. 【免费下载链接】sandwich 项目地址: https://gitcode.com/gh_mirrors/sa/sandwich

Sandwich是一个轻量级且适应性强的密封API库,专为Kotlin中的Retrofit、Ktor和Kotlin多平台处理API响应和异常而设计。本教程将带你从0到1实现Retrofit与Sandwich的集成,轻松管理API响应状态,提升应用的健壮性和用户体验。

为什么选择Sandwich?

在Android开发中,网络请求的响应状态管理是一个常见的挑战。传统的回调方式或简单的try-catch处理不仅代码冗余,还难以优雅地处理各种异常情况。Sandwich通过提供ApiResponse密封类,将网络请求的成功、错误和异常状态统一封装,让开发者可以更专注于业务逻辑,而非繁琐的状态判断。

快速开始:添加依赖

要在Retrofit项目中使用Sandwich,首先需要添加以下依赖。确保你的项目中已经配置了JCenter或Maven Central仓库。

Groovy配置

dependencies {
    implementation "com.github.skydoves:sandwich-retrofit:$version"
}

Kotlin配置

dependencies {
    implementation("com.github.skydoves:sandwich-retrofit:$version")
}

注意:请将$version替换为最新的Sandwich版本号。你可以在项目的gradle/libs.versions.toml文件中查看或更新版本信息。

核心步骤:配置Retrofit

1. 添加CallAdapterFactory

Sandwich提供了ApiResponseCallAdapterFactory,用于将Retrofit的响应转换为ApiResponse类型。在构建Retrofit实例时添加此工厂:

val retrofit = Retrofit.Builder()
    .baseUrl(BASE_URL)
    .addCallAdapterFactory(ApiResponseCallAdapterFactory.create())
    .build()

2. 定义API服务接口

使用suspend关键字定义协程函数,并将返回类型指定为ApiResponse<*>

interface MyApiService {
    @GET("DisneyPosters.json")
    suspend fun fetchData(): ApiResponse<List<Poster>>
}

示例中的Poster模型类可以参考app/src/main/kotlin/com/skydoves/sandwichdemo/model/Poster.kt

3. 执行网络请求并处理响应

通过Retrofit创建服务实例,调用接口方法获取ApiResponse,并使用链式调用来处理不同状态:

val apiService = retrofit.create(MyApiService::class.java)
val response: ApiResponse<List<Poster>> = apiService.fetchData()
response.onSuccess {
    // 处理成功响应,data为响应体内容
    mutableStateFlow.value = data
}.onError {
    // 处理API错误响应(如4xx, 5xx状态码)
    val errorMsg = message()
    // 可通过deserializeErrorBody将错误体转换为自定义模型
}.onException {
    // 处理网络异常(如无网络、超时等)
    val exceptionMsg = message
}

ApiResponse详解

ApiResponse是一个密封类,包含三种状态:SuccessFailure.ErrorFailure.Exception

Success状态

表示网络请求成功,可通过以下属性获取信息:

  • data/body: 响应体数据
  • statusCode: HTTP状态码
  • headers: 响应头
  • raw: OkHttp原始响应

Error状态

表示服务器返回错误状态码(如400, 500),可获取:

  • message(): 错误信息
  • errorBody: 错误响应体
  • statusCode: HTTP状态码

Exception状态

表示网络请求过程中发生异常(如IOException),可通过message获取异常信息。

高级功能:自定义CoroutineScope

Sandwich允许你注入自定义的CoroutineScope,以更好地控制协程生命周期:

.addCallAdapterFactory(ApiResponseCallAdapterFactory.create(
    coroutineScope = yourCustomCoroutineScope
))

也可以通过SandwichInitializer全局设置:

SandwichInitializer.sandwichScope = yourCustomCoroutineScope

这在单元测试中特别有用,可以注入测试协程作用域:

val testScope = TestScope(coroutinesRule.testDispatcher)
val retrofit = Retrofit.Builder()
    .baseUrl(mockWebServer.url("/"))
    .addConverterFactory(MoshiConverterFactory.create())
    .addCallAdapterFactory(ApiResponseCallAdapterFactory.create(testScope))
    .build()

错误体序列化

Sandwich支持使用Kotlin Serialization将错误响应体反序列化为自定义模型。首先添加依赖:

Groovy配置

dependencies {
    implementation "com.github.skydoves:sandwich-retrofit-serialization:$version"
}

Kotlin配置

dependencies {
    implementation("com.github.skydoves:sandwich-retrofit-serialization:$version")
}

定义错误模型类:

@Serializable
data class ErrorMessage(
    val code: Int,
    val message: String
)

然后使用deserializeErrorBodyonErrorDeserialize处理错误:

// 方式一:直接获取反序列化后的错误模型
val errorModel: ErrorMessage? = apiResponse.deserializeErrorBody<String, ErrorMessage>()

// 方式二:在onError回调中处理
apiResponse.onErrorDeserialize<List<Poster>, ErrorMessage> { errorMessage ->
    // 处理错误信息
}

实际应用示例

在项目的app/src/main/kotlin/com/skydoves/sandwichdemo/MainViewModel.kt中,你可以看到完整的集成示例,包括仓库层调用和响应处理。

总结

通过本教程,你已经掌握了如何将Sandwich与Retrofit集成,实现优雅的API响应状态管理。Sandwich的密封类设计让代码更加清晰,错误处理更加便捷,同时提供了灵活的扩展功能满足不同需求。

如果你想深入了解更多高级特性,如全局响应处理、重试机制等,可以参考项目的官方文档:docs/retrofit.md

现在,开始在你的项目中集成Sandwich,提升网络请求处理的效率和质量吧! 🚀

【免费下载链接】sandwich 🥪 Sandwich is an adaptable and lightweight sealed API library designed for handling API responses and exceptions in Kotlin for Retrofit, Ktor, and Kotlin Multiplatform. 【免费下载链接】sandwich 项目地址: https://gitcode.com/gh_mirrors/sa/sandwich

Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐