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.
Install / Use
/learn @skydoves/SandwichREADME
<br>
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
Sandwich has achieved an impressive milestone, being downloaded in over 1,200,000 across Android and backend 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.2.1")
implementation("com.github.skydoves:sandwich-retrofit:2.2.1") // 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")
}
}
}
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
ApiResponseusing theApiResponse.oforApiResponse.suspendOfmethod to ensure the application of these global functions. If you're usingApiResponseFailureSuspendMapperorApiResponseSuspendOperator(common with Ktor/Ktorfit), useApiResponse.suspendOfto ensure suspend mappers and operators are properly awaited.
ApiResponse Extensions
You can effectively handle ApiResponse using the following extensions:
- onSuccess: Execu
