sandwich

sandwich

高效处理网络请求的Kotlin多平台库

Sandwich是一款针对Android和Kotlin Multiplatform项目的网络请求处理库。它为Retrofit、Ktor等框架提供标准化接口,统一处理成功数据、错误和异常情况。通过全局响应处理、Mapper和Operator等特性,Sandwich简化了网络层开发流程。该库与协程完全兼容,使开发者能更专注于核心业务逻辑实现。

SandwichAPI响应处理Kotlin网络请求Android开发Github开源项目

sandwich<br>

<p align="center"> <a href="https://opensource.org/licenses/Apache-2.0"><img alt="License" src="https://img.shields.io/badge/License-Apache%202.0-blue.svg"/></a> <a href="https://android-arsenal.com/api?level=21"><img alt="API" src="https://img.shields.io/badge/API-21%2B-brightgreen.svg?style=flat"/></a> <a href="https://github.com/skydoves/Sandwich/actions"><img alt="Build Status" src="https://github.com/skydoves/sandwich/actions/workflows/build.yml/badge.svg"/></a><br> <a href="https://devlibrary.withgoogle.com/products/android/repos/skydoves-Sandwich"><img alt="Google" src="https://skydoves.github.io/badges/google-devlib.svg"/></a> <a href="https://skydoves.medium.com/handling-success-data-and-error-callback-responses-from-a-network-for-android-projects-using-b53a26214cef"><img alt="Medium" src="https://skydoves.github.io/badges/Story-Medium.svg"/></a> <a href="https://github.com/skydoves"><img alt="Profile" src="https://skydoves.github.io/badges/skydoves.svg"/></a> <a href="https://youtu.be/agjbbn9Swkc"><img alt="Profile" src="https://skydoves.github.io/badges/youtube-android-worldwide.svg"/></a> <a href="https://skydoves.github.io/libraries/sandwich/html/sandwich/com.skydoves.sandwich/index.html"><img alt="Dokka" src="https://skydoves.github.io/badges/dokka-sandwich.svg"/></a> </p>

Why Sandwich?

Sandwich was conceived to streamline the creation of standardized interfaces to model responses from Retrofit, Ktor, and whatever. This library empowers you to handle body data, errors, and exceptional cases more succinctly, utilizing functional operators within a multi-layer architecture. With Sandwich, the need to create wrapper classes like Resource or Result is eliminated, allowing you to concentrate on your core business logic. Sandwich boasts features such as global response handling, Mapper, Operator, and exceptional compatibility, including ApiResponse With Coroutines.

Download

Maven Central

Sandwich has achieved an impressive milestone, being downloaded in over 500,000 Android projects worldwide! <br>

<img src="https://user-images.githubusercontent.com/24237865/103460609-f18ee000-4d5a-11eb-81e2-17696e3a5804.png" width="774" height="224"/>

Gradle

Add the dependency below into your module's build.gradle file:

dependencies { implementation("com.github.skydoves:sandwich:2.0.8") implementation("com.github.skydoves:sandwich-retrofit:2.0.8") // For Retrofit (Android) }

For Kotlin Multiplatform, add the dependency below to your module's build.gradle.kts file:

sourceSets { val commonMain by getting { dependencies { implementation("com.github.skydoves:sandwich:$version") implementation("com.github.skydoves:sandwich-ktor:$version") implementation("com.github.skydoves:sandwich-ktorfit:$version") } } }

SNAPSHOT

Sandwich <br>

<details> <summary>See how to import the snapshot</summary>

Including the SNAPSHOT

Snapshots of the current development version of Sandwich are available, which track the latest versions.

To import snapshot versions on your project, add the code snippet below on your gradle file:

repositories { maven { url 'https://oss.sonatype.org/content/repositories/snapshots/' } }

Next, add the dependency below to your module's build.gradle file:

dependencies { implementation "com.github.skydoves:sandwich:1.3.10-SNAPSHOT" }
</details>

R8 / ProGuard

The specific rules are already bundled into the JAR which can be interpreted by R8 automatically.

Documentation

For comprehensive details about Sandwich, please refer to the complete documentation available here.

Use Cases

You can also check out nice use cases of this library in the repositories below:

  • Pokedex: 🗡️ Android Pokedex using Hilt, Motion, Coroutines, Flow, Jetpack (Room, ViewModel, LiveData) based on MVVM architecture.
  • ChatGPT Android: 📲 ChatGPT Android demonstrates OpenAI's ChatGPT on Android with Stream Chat SDK for Compose.
  • DisneyMotions: 🦁 A Disney app using transformation motions based on MVVM (ViewModel, Coroutines, LiveData, Room, Repository, Koin) architecture.
  • MarvelHeroes: ❤️ A sample Marvel heroes application based on MVVM (ViewModel, Coroutines, LiveData, Room, Repository, Koin) architecture.
  • Neko: Free, open source, unofficial MangaDex reader for Android.
  • TheMovies2: 🎬 A demo project using The Movie DB based on Kotlin MVVM architecture and material design & animations.

Usage

For comprehensive details about Sandwich, please refer to the complete documentation available here.

ApiResponse

ApiResponse serves as an interface designed to create consistent responses from API or I/O calls, such as network, database, or whatever. It offers convenient extensions to manage your payloads, encompassing both body data and exceptional scenarios. ApiResponse encompasses three distinct types: Success, Failure.Error, and Failure.Exception.

ApiResponse.Success

This represents a successful response from API or I/O tasks. You can create an instance of [ApiResponse.Success] by giving the generic type and data.

val apiResponse = ApiResponse.Success(data = myData) val data = apiResponse.data

Depending on your model designs, you can also utilize tag property. The tag is an additional value that can be held to distinguish the origin of the data or to facilitate post-processing of successful data.

val apiResponse = ApiResponse.Success(data = myData, tag = myTag) val tag = apiResponse.tag

ApiResponse.Failure.Exception

This signals a failed tasks captured by unexpected exceptions during API request creation or response processing on the client side, such as a network connection failure. You can obtain exception details from the ApiResponse.Failure.Exception.

val apiResponse = ApiResponse.Failure.Exception(exception = HttpTimeoutException()) val exception = apiResponse.exception val message = apiResponse.message

ApiResponse.Failure.Error

This denotes a failed API or I/O request, typically due to bad requests or internal server errors. You can additionally put an error payload that can contain detailed error information.

val apiResponse = ApiResponse.Failure.Error(payload = errorBody) val payload = apiResponse.payload

You can also define custom error responses that extend ApiResponse.Failure.Error or ApiResponse.Failure.Exception, as demonstrated in the example below:

data object LimitedRequest : ApiResponse.Failure.Error( payload = "your request is limited", ) data object WrongArgument : ApiResponse.Failure.Error( payload = "wrong argument", ) data object HttpException : ApiResponse.Failure.Exception( throwable = RuntimeException("http exception") )

The custom error response is very useful when you want to explicitly define and handle error responses, especially when working with map extensions.

val apiResponse = service.fetchMovieList() apiResponse.onSuccess { // .. }.flatMap { // if the ApiResponse is Failure.Error and contains error body, then maps it to a custom error response. if (this is ApiResponse.Failure.Error) { val errorBody = (payload as? Response)?.body?.string() if (errorBody != null) { val errorMessage: ErrorMessage = Json.decodeFromString(errorBody) when (errorMessage.code) { 10000 -> LimitedRequest 10001 -> WrongArgument } } } this }

Then you can handle the errors based on your custom message in other layers:

val apiResponse = repository.fetchMovieList() apiResponse.onError { when (this) { LimitedRequest -> // update your UI WrongArgument -> // update your UI } }

You might not want to use the flatMap extension for all API requests. If you aim to standardize custom error types across all API requests, you can explore the Global Failure Mapper.

Creation of ApiResponse

Sandwich provides convenient ways to create an ApiResponse using functions such as ApiResponse.of or apiResponseOf, as shown below:

val apiResponse = ApiResponse.of { service.request() } val apiResponse = apiResponseOf { service.request() }

If you need to run suspend functions inside the lambda, you can use ApiResponse.suspendOf or suspendApiResponseOf instead:

val apiResponse = ApiResponse.suspendOf { service.request() } val apiResponse = suspendApiResponseOf { service.request() }

Note: If you intend to utilize the global operator or global ApiResponse mapper in Sandwich, you should create an ApiResponse using the ApiResponse.of method to ensure the application of these global functions.

ApiResponse Extensions

You can effectively handling ApiResponse using the following extensions:

  • onSuccess: Executes when the ApiResponse is of type ApiResponse.Success. Within this scope, you can directly access the body data.
  • onError: Executes when the ApiResponse is of type ApiResponse.Failure.Error. Here, you can access the messareOrNull and payload here.
  • onException: Executes when the ApiResponse is of type ApiResponse.Failure.Exception. You can access the messareOrNull and exception here.
  • onFailure: Executes when the ApiResponse is either ApiResponse.Failure.Error or ApiResponse.Failure.Exception. You can access the messareOrNull here.

Each scope operates according to its corresponding ApiResponse type:

val response = disneyService.fetchDisneyPosterList() response.onSuccess { // this scope will be executed if the request successful. // handle the success case }.onError { // this scope will be executed when the request failed with errors. // handle the error case }.onException { // this scope will be executed when the request failed with exceptions. // handle the exception case }

If you don't want to specify each failure case, you can simplify it by using the onFailure extension:

val response = disneyService.fetchDisneyPosterList() response.onSuccess { // this scope will be executed if the request successful. // handle the success case }.onFailure { }

ApiResponse Extensions With Coroutines

With the ApiResponse type, you can leverage Coroutines extensions to handle responses seamlessly within coroutine scopes. These extensions provide a convenient way to process different response types. Here's how you can use them:

  • suspendOnSuccess: This extension runs if the ApiResponse is of type ApiResponse.Success. You can access the body data directly within this scope.

  • suspendOnError: This extension is executed if the ApiResponse is of type ApiResponse.Failure.Error. You can access the error message and the error body in this scope.

  • suspendOnException: If the ApiResponse is of type ApiResponse.Failure.Exception, this extension is triggered. You can access the exception message in this scope.

  • suspendOnFailure: This extension is executed if the ApiResponse is either ApiResponse.Failure.Error or ApiResponse.Failure.Exception. You can access the error message in this scope.

Each extension scope operates based on the corresponding ApiResponse type. By utilizing these extensions, you can handle responses effectively within different coroutine contexts.

flow { val response = disneyService.fetchDisneyPosterList() response.suspendOnSuccess { posterDao.insertPosterList(data) // insertPosterList(data) is a suspend function. emit(data) }.suspendOnError { // handles error cases }.suspendOnException { // handles exceptional cases } }.flowOn(Dispatchers.IO)

Flow

Sandwich offers some useful extensions to transform your ApiResponse into a Flow by using the toFlow extension:

val flow = disneyService.fetchDisneyPosterList() .onError { // handles error cases when the API request gets an error response. }.onException { // handles exceptional cases when the API request gets an exception response. }.toFlow() // returns a coroutines flow .flowOn(Dispatchers.IO)

If you want to transform the original data and work with a Flow containing the transformed data, you can do so as shown in the examples below:

val response = pokedexClient.fetchPokemonList(page = page) response.toFlow { pokemons -> pokemons.forEach { pokemon -> pokemon.page = page } pokemonDao.insertPokemonList(pokemons) pokemonDao.getAllPokemonList(page) }.flowOn(Dispatchers.IO)

Retrieving

Sandwich provides effortless methods to directly extract the encapsulated body data from the ApiResponse. You can take advantage of the following functionalities:

getOrNull

Returns the encapsulated data if this instance represents ApiResponse.Success or returns null if this is failed.

val data: List<Poster>? = disneyService.fetchDisneyPosterList().getOrNull()

getOrElse

Returns the encapsulated data if this instance represents ApiResponse.Success or returns a default value if this is failed.

val data: List<Poster> = disneyService.fetchDisneyPosterList().getOrElse(emptyList())

getOrThrow

Returns the encapsulated data if this instance represents ApiResponse.Success or throws the encapsulated Throwable exception if this is failed.

try { val data: List<Poster> = disneyService.fetchDisneyPosterList().getOrThrow() } catch (e: Exception) { e.printStackTrace() }

Retry

Sandwich offers seamless ways to run and retry tasks. To execute and retry network or I/O requests, you can employ the RetryPolicy interface along with the runAndRetry extension, as demonstrated in the code below:

val retryPolicy = object : RetryPolicy { override fun shouldRetry(attempt: Int, message: String?): Boolean = attempt <= 3 override fun retryTimeout(attempt: Int, message: String?): Int = 3000 } val apiResponse = runAndRetry(retryPolicy) { attempt, reason -> mainRepository.fetchPosters() }.onSuccess { // Handle a success case }.onFailure { // Handle failure cases }

Sequential

Sandwich provides sequential solutions for scenarios where you require sequential execution of network requests.

then and suspendThen

If you have a scenario where you need to execute tasks A, B, and C in a dependent sequence, for example, where task B depends on the completion of task A, and task C depends on the completion of task B, you can effectively utilize the then or suspendThen extensions, as demonstrated in the example below:

service.getUserToken(id) suspendThen { tokenResponse -> service.getUserDetails(tokenResponse.token) } suspendThen { userResponse -> service.queryPosters(userResponse.user.name) }.mapSuccess { posterResponse -> posterResponse.posters }.onSuccess { posterStateFlow.value = data }.onFailure { Log.e("sequential", message()) }

Operator

The Operator feature stands out as one of the most powerful capabilities provided by Sandwich. It empowers you to establish well-defined, preconfigured processors for your ApiResponse instances. This enables you to encapsulate and reuse a consistent sequence of procedures across your API requests.

You can streamline the handling of onSuccess, onError, and onException scenarios by utilizing the operator extension alongside the ApiResponseOperator. Operator proves particularly valuable when

编辑推荐精选

蛙蛙写作

蛙蛙写作

AI小说写作助手,一站式润色、改写、扩写

蛙蛙写作—国内先进的AI写作平台,涵盖小说、学术、社交媒体等多场景。提供续写、改写、润色等功能,助力创作者高效优化写作流程。界面简洁,功能全面,适合各类写作者提升内容品质和工作效率。

AI辅助写作AI工具蛙蛙写作AI写作工具学术助手办公助手营销助手AI助手
Trae

Trae

字节跳动发布的AI编程神器IDE

Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。

AI工具TraeAI IDE协作生产力转型热门
问小白

问小白

全能AI智能助手,随时解答生活与工作的多样问题

问小白,由元石科技研发的AI智能助手,快速准确地解答各种生活和工作问题,包括但不限于搜索、规划和社交互动,帮助用户在日常生活中提高效率,轻松管理个人事务。

热门AI助手AI对话AI工具聊天机器人
Transly

Transly

实时语音翻译/同声传译工具

Transly是一个多场景的AI大语言模型驱动的同声传译、专业翻译助手,它拥有超精准的音频识别翻译能力,几乎零延迟的使用体验和支持多国语言可以让你带它走遍全球,无论你是留学生、商务人士、韩剧美剧爱好者,还是出国游玩、多国会议、跨国追星等等,都可以满足你所有需要同传的场景需求,线上线下通用,扫除语言障碍,让全世界的语言交流不再有国界。

讯飞智文

讯飞智文

一键生成PPT和Word,让学习生活更轻松

讯飞智文是一个利用 AI 技术的项目,能够帮助用户生成 PPT 以及各类文档。无论是商业领域的市场分析报告、年度目标制定,还是学生群体的职业生涯规划、实习避坑指南,亦或是活动策划、旅游攻略等内容,它都能提供支持,帮助用户精准表达,轻松呈现各种信息。

AI办公办公工具AI工具讯飞智文AI在线生成PPTAI撰写助手多语种文档生成AI自动配图热门
讯飞星火

讯飞星火

深度推理能力全新升级,全面对标OpenAI o1

科大讯飞的星火大模型,支持语言理解、知识问答和文本创作等多功能,适用于多种文件和业务场景,提升办公和日常生活的效率。讯飞星火是一个提供丰富智能服务的平台,涵盖科技资讯、图像创作、写作辅助、编程解答、科研文献解读等功能,能为不同需求的用户提供便捷高效的帮助,助力用户轻松获取信息、解决问题,满足多样化使用场景。

热门AI开发模型训练AI工具讯飞星火大模型智能问答内容创作多语种支持智慧生活
Spark-TTS

Spark-TTS

一种基于大语言模型的高效单流解耦语音令牌文本到语音合成模型

Spark-TTS 是一个基于 PyTorch 的开源文本到语音合成项目,由多个知名机构联合参与。该项目提供了高效的 LLM(大语言模型)驱动的语音合成方案,支持语音克隆和语音创建功能,可通过命令行界面(CLI)和 Web UI 两种方式使用。用户可以根据需求调整语音的性别、音高、速度等参数,生成高质量的语音。该项目适用于多种场景,如有声读物制作、智能语音助手开发等。

咔片PPT

咔片PPT

AI助力,做PPT更简单!

咔片是一款轻量化在线演示设计工具,借助 AI 技术,实现从内容生成到智能设计的一站式 PPT 制作服务。支持多种文档格式导入生成 PPT,提供海量模板、智能美化、素材替换等功能,适用于销售、教师、学生等各类人群,能高效制作出高品质 PPT,满足不同场景演示需求。

讯飞绘文

讯飞绘文

选题、配图、成文,一站式创作,让内容运营更高效

讯飞绘文,一个AI集成平台,支持写作、选题、配图、排版和发布。高效生成适用于各类媒体的定制内容,加速品牌传播,提升内容营销效果。

热门AI辅助写作AI工具讯飞绘文内容运营AI创作个性化文章多平台分发AI助手
材料星

材料星

专业的AI公文写作平台,公文写作神器

AI 材料星,专业的 AI 公文写作辅助平台,为体制内工作人员提供高效的公文写作解决方案。拥有海量公文文库、9 大核心 AI 功能,支持 30 + 文稿类型生成,助力快速完成领导讲话、工作总结、述职报告等材料,提升办公效率,是体制打工人的得力写作神器。

下拉加载更多