<br>
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.
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"/>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") } } }
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:
</details>dependencies { implementation "com.github.skydoves:sandwich:1.3.10-SNAPSHOT" }
The specific rules are already bundled into the JAR which can be interpreted by R8 automatically.
For comprehensive details about Sandwich, please refer to the complete documentation available here.
You can also check out nice use cases of this library in the repositories below:
For comprehensive details about Sandwich, please refer to the complete documentation available here.
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.
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
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
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.
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
ApiResponseusing theApiResponse.ofmethod to ensure the application of these global functions.
You can effectively handling ApiResponse using the following extensions:
ApiResponse is of type ApiResponse.Success. Within this scope, you can directly access the body data.ApiResponse is of type ApiResponse.Failure.Error. Here, you can access the messareOrNull and payload here.ApiResponse is of type ApiResponse.Failure.Exception. You can access the messareOrNull and exception here.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 { }
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)
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)
Sandwich provides effortless methods to directly extract the encapsulated body data from the ApiResponse. You can take advantage of the following functionalities:
Returns the encapsulated data if this instance represents ApiResponse.Success or returns null if this is failed.
val data: List<Poster>? = disneyService.fetchDisneyPosterList().getOrNull()
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())
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() }
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 }
Sandwich provides sequential solutions for scenarios where you require sequential execution of network requests.
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()) }
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辅助编程,代码自动修复
Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。


AI一键生成PPT,就用博思AIPPT!
博思AIPPT,新一代的AI生成PPT平台,支持智能生成PPT、AI美化PPT、文本&链接生成PPT、导入Word/PDF/Markdown文档生成PPT等,内置海量精美PPT模板,涵盖商务、教育、科技等不同风格,同时针对每个页面提供多种版式,一键自适应切换,完美适配各种办公场景。


AI赋能电商视觉革命,一站式智能商拍平台
潮际好麦深耕服装行业,是国内AI试衣效果最好的软件。使用先进AIGC能力为电商卖家批量提供优质的、低成本的商拍图。合作品牌有Shein、Lazada、安踏、百丽等65个国内外头部品牌,以及国内10万+淘宝、天猫、京东等主流平台的品牌商家,为卖家节省将近85%的出图成本,提升约3倍出图效率,让品牌能够快速上架。

