

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 , , , and exceptional compatibility, including .
Download

Sandwich has achieved an impressive milestone, being downloaded in over 1,200,000 across Android and backend projects worldwide!
Gradle
Add the dependency below into your module's build.gradle file:
dependencies {
implementation("com.github.skydoves:sandwich:2.3.0")
implementation("com.github.skydoves:sandwich-retrofit:2.3.0") // For Retrofit (Android)
testImplementation("com.github.skydoves:sandwich-test:2.3.0") // For Testing
}
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")
}
}
val commonTest by getting {
dependencies {
implementation("com.github.skydoves:sandwich-test:$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.
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 (this is ApiResponse.Failure.Error) {
val errorBody = (payload as? Response)?.body?.string()
if (errorBody != null) {
val errorMessage: ErrorMessage = Json.decodeFromString(errorBody)
(errorMessage.code) {
-> LimitedRequest
-> WrongArgument
}
}
}
}
Then you can handle the errors based on your custom message in other layers:
val apiResponse = repository.fetchMovieList()
apiResponse.onError {
when (this) {
LimitedRequest ->
WrongArgument ->
}
}
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 or ApiResponse.suspendOf method to ensure the application of these global functions. If you're using ApiResponseFailureSuspendMapper or ApiResponseSuspendOperator (common with Ktor/Ktorfit), use to ensure suspend mappers and operators are properly awaited.
ApiResponse Extensions
You can effectively handle ApiResponse using the following extensions:
Each scope operates according to its corresponding ApiResponse type:
val response = disneyService.fetchDisneyPosterList()
response.onSuccess {
}.onError {
}.onException {
}
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 {
}.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:
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)
emit(data)
}.suspendOnError {
}.suspendOnException {
}
}.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 {
}.onException {
}.toFlow()
.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)
Functional Extensions
Sandwich provides a variety of functional extensions for transforming and composing ApiResponse:
val response = disneyService.fetchDisneyPosterList()
.validate({ it.isNotEmpty() }) { "List cannot be empty" }
.filter { poster -> poster.isActive }
.recover(emptyList())
.peekSuccess { posters -> analytics.track(posters.size) }
All extensions have corresponding suspend variants (e.g., suspendRecover, suspendValidate) for coroutine support. For comprehensive details, refer to the ApiResponse documentation.
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: ?): = attempt <=
: =
}
apiResponse = runAndRetry(retryPolicy) { attempt, reason ->
mainRepository.fetchPosters()
}.onSuccess {
}.onFailure {
}
This setup allows you to define a retry policy that determines whether a retry attempt should occur and specifies the retry timeout. The runAndRetry extension then encapsulates the execution logic, applying the defined policy, and providing the response in a clean and structured manner.
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. proves particularly valuable when you're aiming for global handling of instances and wish to minimize boilerplate code within your and classes. Here are a few illustrative examples:
By embracing the Operator pattern, you can significantly simplify the management of various ApiResponse outcomes and promote cleaner, more maintainable code within your application's architecture.
Operator With Coroutines
For scenarios where you aim to delegate and operate a suspension lambda using the operator pattern, the suspendOperator extension and the ApiResponseSuspendOperator class come into play. These tools facilitate the process, as showcased in the examples below:
class CommonResponseOperator<T>(
private val success: suspend (ApiResponse.Success<T>) -> Unit
) : ApiResponseSuspendOperator<T>() {
override suspend fun onSuccess(apiResponse: .<>) = success(apiResponse)
}
You can use suspend functions like emit in the success scope.
val response = disneyService.fetchDisneyPosterList().suspendOperator(
CommonResponseOperator(
success = {
emit(data)
Timber.d("success data: $data")
}
)
)
Incorporating the suspendOperator extension alongside the ApiResponseSuspendOperator class allows you to efficiently manage suspension lambdas in conjunction with the operator pattern, promoting a more concise and maintainable approach within your codebase.
Global Operator
The global operator is undoubtedly a robust feature offered by Sandwich. It empowers you to operate on operators globally across all ApiResponse instances in your application by employing the SandwichInitializer. This way, you can avoid the necessity of creating operator instances for every API call or employing dependency injection for common operations. The following examples illustrate how to use a global operator to handle both ApiResponse.Failure.Error and ApiResponse.Failure.Exception scenarios. You can leverage the global operator to refresh your user token or implement any other additional processes necessary for specific API requests within your application. The example below demonstrates how you can automatically check and refresh the user token depending on the response status using Sandwich's global operator:
Initialize Global Operator
First, it's highly recommended to initialize the global operator in the Application class or using another initialization solution like App Startup. This ensures that the global operator is set up before any API requests are made.
class SandwichDemoApp : Application() {
override fun onCreate() {
super.onCreate()
SandwichInitializer.sandwichOperators += listOf(TokenRefreshGlobalOperator<Any>(this))
}
}
By configuring the global operator within SandwichInitializer, you enable your application to consistently process and handle various ApiResponse situations. This can include tasks such as managing success cases, handling errors, or dealing with exceptions, all on a global scale.
Implement Your Global Operator
Create your custom GlobalResponseOperator class that extends operators such as ApiResponseSuspendOperator and ApiResponseOperator. This operator will allow you to define common response handling logic that can be applied globally.
In this example, the global operator's onError function is used to automatically check for Unauthorized and Forbidden status code (HTTP 401 and 403) in the error response. If an unauthorized error occurs, the user token is refreshed, and the failed request is retried with the updated token using runAndRetry. This way, you can seamlessly manage token expiration and refresh for your API requests.
Global Operator With Hilt and App Startup
If you want to initialize the global operator by using with Hilt and App Startup, you can follow the instructions below.
1. Implement an Entry Point
First, you should implement an entry point for injecting the global operator into an App Startup initializer.
@EntryPoint
@InstallIn(SingletonComponent::class)
interface NetworkEntryPoint {
fun inject(networkInitializer: )
{
: NetworkEntryPoint {
appContext = context.applicationContext ?: IllegalStateException(
,
)
EntryPointAccessors.fromApplication(
appContext,
NetworkEntryPoint::.java,
)
}
}
}
2. Provide Global Operator Dependency
Next, provide your global operator with Hilt like the example below:
@Module
@InstallIn(SingletonComponent::class)
object NetworkModule {
@Provides
@Singleton
fun provideTokenRefreshGlobalOperator(
@ApplicationContext context: Context,
authService: AuthService,
userDataStore: UserDataStore
): TokenRefreshGlobalOperator<Any> {
return TokenRefreshGlobalOperator(
context = context,
authService = authService,
userDataStore = userDataStore,
coroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.IO),
)
}
}
3. Implement App Startup Initializer
Finally, implement the App Startup Initializer and initialize the Initializer following the App Startup guidance.
public class NetworkInitializer : Initializer<Unit> {
@set:Inject
internal lateinit tokenRefreshGlobalOperator: TokenRefreshGlobalOperator<Any>
{
NetworkEntryPoint.resolve(context).inject()
SandwichInitializer.sandwichOperators += listOf(tokenRefreshGlobalOperator)
}
: List<Class< Initializer<*>>> = emptyList()
}
Find this library useful? :heart:
Support it by joining stargazers for this repository. :star:
And follow me for my next creations! 🤩
License
Copyright 2020 skydoves (Jaewoong Eum)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.