{"id":13611610,"url":"https://github.com/skydoves/sandwich","last_synced_at":"2025-05-14T04:00:33.974Z","repository":{"id":38534489,"uuid":"261363701","full_name":"skydoves/sandwich","owner":"skydoves","description":"🥪  Sandwich is an adaptable and lightweight sealed API library designed for handling API responses and exceptions in Kotlin for Retrofit, Ktor, and Kotlin Multiplatform.","archived":false,"fork":false,"pushed_at":"2025-05-12T23:34:03.000Z","size":2478,"stargazers_count":1648,"open_issues_count":6,"forks_count":105,"subscribers_count":14,"default_branch":"main","last_synced_at":"2025-05-13T00:29:14.911Z","etag":null,"topics":["android","api","apiresponse","datasource","kotlin","network","retrofit","skydoves"],"latest_commit_sha":null,"homepage":"https://skydoves.github.io/sandwich/","language":"Kotlin","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/skydoves.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":".github/CODEOWNERS","security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null},"funding":{"github":"skydoves","custom":["https://www.paypal.me/skydoves","https://www.buymeacoffee.com/skydoves"]}},"created_at":"2020-05-05T04:45:16.000Z","updated_at":"2025-05-07T22:42:46.000Z","dependencies_parsed_at":"2023-09-26T00:40:00.102Z","dependency_job_id":"d9c6bb2d-72fb-4fb8-bd57-c80c4a4033f3","html_url":"https://github.com/skydoves/sandwich","commit_stats":{"total_commits":502,"total_committers":7,"mean_commits":71.71428571428571,"dds":"0.14541832669322707","last_synced_commit":"04245dd143f506382889af006a677c3de9f9dc1c"},"previous_names":[],"tags_count":43,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/skydoves%2Fsandwich","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/skydoves%2Fsandwich/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/skydoves%2Fsandwich/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/skydoves%2Fsandwich/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/skydoves","download_url":"https://codeload.github.com/skydoves/sandwich/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254067086,"owners_count":22009074,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["android","api","apiresponse","datasource","kotlin","network","retrofit","skydoves"],"created_at":"2024-08-01T19:01:58.826Z","updated_at":"2025-05-14T04:00:33.914Z","avatar_url":"https://github.com/skydoves.png","language":"Kotlin","funding_links":["https://github.com/sponsors/skydoves","https://www.paypal.me/skydoves","https://www.buymeacoffee.com/skydoves"],"categories":["Libraries","Kotlin"],"sub_categories":["🚀 Language extensions"],"readme":"![sandwich](https://user-images.githubusercontent.com/24237865/162602054-2010d249-8a81-4673-b9ae-1edff1080ab7.png)\u003cbr\u003e\n\n\u003cp align=\"center\"\u003e\n  \u003ca href=\"https://opensource.org/licenses/Apache-2.0\"\u003e\u003cimg alt=\"License\" src=\"https://img.shields.io/badge/License-Apache%202.0-blue.svg\"/\u003e\u003c/a\u003e\n  \u003ca href=\"https://android-arsenal.com/api?level=21\"\u003e\u003cimg alt=\"API\" src=\"https://img.shields.io/badge/API-21%2B-brightgreen.svg?style=flat\"/\u003e\u003c/a\u003e\n  \u003ca href=\"https://github.com/skydoves/Sandwich/actions\"\u003e\u003cimg alt=\"Build Status\" src=\"https://github.com/skydoves/sandwich/actions/workflows/build.yml/badge.svg\"/\u003e\u003c/a\u003e\n  \u003ca href=\"https://github.com/doveletter\"\u003e\u003cimg alt=\"Profile\" src=\"https://skydoves.github.io/badges/dove-letter.svg\"/\u003e\u003c/a\u003e\u003cbr\u003e\n  \u003ca href=\"https://devlibrary.withgoogle.com/products/android/repos/skydoves-Sandwich\"\u003e\u003cimg alt=\"Google\" src=\"https://skydoves.github.io/badges/google-devlib.svg\"/\u003e\u003c/a\u003e\n  \u003ca href=\"https://skydoves.medium.com/handling-success-data-and-error-callback-responses-from-a-network-for-android-projects-using-b53a26214cef\"\u003e\u003cimg alt=\"Medium\" src=\"https://skydoves.github.io/badges/Story-Medium.svg\"/\u003e\u003c/a\u003e\n  \u003ca href=\"https://github.com/skydoves\"\u003e\u003cimg alt=\"Profile\" src=\"https://skydoves.github.io/badges/skydoves.svg\"/\u003e\u003c/a\u003e\n  \u003ca href=\"https://youtu.be/agjbbn9Swkc\"\u003e\u003cimg alt=\"Profile\" src=\"https://skydoves.github.io/badges/youtube-android-worldwide.svg\"/\u003e\u003c/a\u003e \n  \u003ca href=\"https://skydoves.github.io/libraries/sandwich/html/sandwich/com.skydoves.sandwich/index.html\"\u003e\u003cimg alt=\"Dokka\" src=\"https://skydoves.github.io/badges/dokka-sandwich.svg\"/\u003e\u003c/a\u003e\n\u003c/p\u003e\n\n## Why Sandwich?\nSandwich was conceived to streamline the creation of standardized interfaces to model responses from [Retrofit](https://skydoves.github.io/sandwich/sandwich/retrofit/), [Ktor](https://skydoves.github.io/sandwich/sandwich/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](https://skydoves.github.io/sandwich/operator#global-operator), [Mapper](https://skydoves.github.io/sandwich/mapper), [Operator](https://skydoves.github.io/sandwich/operator), and exceptional compatibility, including [ApiResponse With Coroutines](https://skydoves.github.io/sandwich/apiresponse/#apiresponse-extensions-with-coroutines).\n\n## Download\n[![Maven Central](https://img.shields.io/maven-central/v/com.github.skydoves/sandwich.svg?label=Maven%20Central)](https://search.maven.org/search?q=g:%22com.github.skydoves%22%20AND%20a:%22sandwich%22)\n\nSandwich has achieved an impressive milestone, being downloaded in __over 1,200,000__ across Android and backend projects worldwide! \u003cbr\u003e\n\n\u003cimg src=\"https://user-images.githubusercontent.com/24237865/103460609-f18ee000-4d5a-11eb-81e2-17696e3a5804.png\" width=\"774\" height=\"224\"/\u003e\n\n### Gradle\n\nAdd the dependency below into your **module**'s `build.gradle` file:\n\n```gradle\ndependencies {\n    implementation(\"com.github.skydoves:sandwich:2.1.1\")\n    implementation(\"com.github.skydoves:sandwich-retrofit:2.1.1\") // For Retrofit (Android)\n}\n```\n\nFor Kotlin Multiplatform, add the dependency below to your module's `build.gradle.kts` file:\n\n```kotlin\nsourceSets {\n    val commonMain by getting {\n        dependencies {\n            implementation(\"com.github.skydoves:sandwich:$version\")\n            implementation(\"com.github.skydoves:sandwich-ktor:$version\")\n            implementation(\"com.github.skydoves:sandwich-ktorfit:$version\")\n        }\n    }\n}\n```\n\n## R8 / ProGuard\nThe specific rules are [already bundled](sandwich/src/main/resources/META-INF/proguard/sandwich.pro) into the JAR which can be interpreted by R8 automatically.\n\n## Documentation\n\nFor comprehensive details about Sandwich, please refer to the complete [documentation available here](https://skydoves.github.io/sandwich/).\n\n## Use Cases\nYou can also check out nice use cases of this library in the repositories below:\n- [Pokedex](https://github.com/skydoves/pokedex): 🗡️ Android Pokedex using Hilt, Motion, Coroutines, Flow, Jetpack (Room, ViewModel, LiveData) based on MVVM architecture.\n- [ChatGPT Android](https://github.com/skydoves/chatgpt-android): 📲 ChatGPT Android demonstrates OpenAI's ChatGPT on Android with Stream Chat SDK for Compose.\n- [DisneyMotions](https://github.com/skydoves/DisneyMotions): 🦁 A Disney app using transformation motions based on MVVM (ViewModel, Coroutines, LiveData, Room, Repository, Koin) architecture.\n- [MarvelHeroes](https://github.com/skydoves/marvelheroes): ❤️ A sample Marvel heroes application based on MVVM (ViewModel, Coroutines, LiveData, Room, Repository, Koin)  architecture.\n- [Neko](https://github.com/CarlosEsco/Neko): Free, open source, unofficial MangaDex reader for Android.\n- [TheMovies2](https://github.com/skydoves/TheMovies2): 🎬 A demo project using The Movie DB based on Kotlin MVVM architecture and material design \u0026 animations.\n\n## Usage\n\nFor comprehensive details about Sandwich, please refer to the complete [documentation available here](https://skydoves.github.io/sandwich/).\n\n- [Retrofit Integration](https://skydoves.github.io/sandwich/retrofit)\n- [Ktor Integration](https://skydoves.github.io/sandwich/ktor)\n- [Ktorfit Integration](https://skydoves.github.io/sandwich/ktorfit)\n\n### ApiResponse\n\n`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**.\n\n#### ApiResponse.Success\n\nThis 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.\n\n```kotlin\nval apiResponse = ApiResponse.Success(data = myData)\nval data = apiResponse.data\n```\n\nDepending 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.\n\n```kotlin\nval apiResponse = ApiResponse.Success(data = myData, tag = myTag)\nval tag = apiResponse.tag\n```\n\n#### ApiResponse.Failure.Exception\n\nThis 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`.\n\n```kotlin\nval apiResponse = ApiResponse.Failure.Exception(exception = HttpTimeoutException())\nval exception = apiResponse.exception\nval message = apiResponse.message\n```\n\n#### ApiResponse.Failure.Error\n\nThis 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.\n\n```kotlin\nval apiResponse = ApiResponse.Failure.Error(payload = errorBody)\nval payload = apiResponse.payload\n```\n\nYou can also define custom error responses that extend `ApiResponse.Failure.Error` or `ApiResponse.Failure.Exception`, as demonstrated in the example below:\n\n```kotlin\ndata object LimitedRequest : ApiResponse.Failure.Error(\n  payload = \"your request is limited\",\n)\n\ndata object WrongArgument : ApiResponse.Failure.Error(\n  payload = \"wrong argument\",\n)\n\ndata object HttpException : ApiResponse.Failure.Exception(\n  throwable = RuntimeException(\"http exception\")\n)\n```\n\nThe custom error response is very useful when you want to explicitly define and handle error responses, especially when working with map extensions.\n\n```kotlin\nval apiResponse = service.fetchMovieList()\napiResponse.onSuccess {\n    // ..\n}.flatMap {\n  // if the ApiResponse is Failure.Error and contains error body, then maps it to a custom error response.  \n  if (this is ApiResponse.Failure.Error) {\n    val errorBody = (payload as? Response)?.body?.string()\n    if (errorBody != null) {\n      val errorMessage: ErrorMessage = Json.decodeFromString(errorBody)\n      when (errorMessage.code) {\n        10000 -\u003e LimitedRequest\n        10001 -\u003e WrongArgument\n      }\n    }\n  }\n  this\n}\n```\n\nThen you can handle the errors based on your custom message in other layers:\n\n```kotlin\nval apiResponse = repository.fetchMovieList()\napiResponse.onError {\n  when (this) {\n    LimitedRequest -\u003e // update your UI\n    WrongArgument -\u003e // update your UI\n  }\n}\n```\n\nYou 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](https://skydoves.github.io/sandwich/mapper/#global-failure-mapper).\n\n#### Creation of ApiResponse\n\nSandwich provides convenient ways to create an `ApiResponse` using functions such as `ApiResponse.of` or `apiResponseOf`, as shown below:\n\n```kotlin\nval apiResponse = ApiResponse.of { service.request() }\nval apiResponse = apiResponseOf { service.request() }\n```\n\nIf you need to run suspend functions inside the lambda, you can use `ApiResponse.suspendOf` or `suspendApiResponseOf` instead:\n\n```kotlin\nval apiResponse = ApiResponse.suspendOf { service.request() }\nval apiResponse = suspendApiResponseOf { service.request() }\n```\n\n\u003e **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.\n\n#### ApiResponse Extensions\n\nYou can effectively handling `ApiResponse` using the following extensions:\n\n- **onSuccess**: Executes when the `ApiResponse` is of type `ApiResponse.Success`. Within this scope, you can directly access the body data.\n- **onError**: Executes when the `ApiResponse` is of type `ApiResponse.Failure.Error`. Here, you can access the `messareOrNull` and `payload` here.\n- **onException**: Executes when the `ApiResponse` is of type `ApiResponse.Failure.Exception`. You can access the `messareOrNull` and `exception` here.\n- **onFailure**: Executes when the `ApiResponse` is either `ApiResponse.Failure.Error` or `ApiResponse.Failure.Exception`. You can access the `messareOrNull` here.\n\nEach scope operates according to its corresponding `ApiResponse` type:\n\n```kotlin\nval response = disneyService.fetchDisneyPosterList()\nresponse.onSuccess {\n    // this scope will be executed if the request successful.\n    // handle the success case\n  }.onError {\n    // this scope will be executed when the request failed with errors.\n    // handle the error case\n  }.onException {\n   // this scope will be executed when the request failed with exceptions.\n   // handle the exception case\n  }\n```\n\nIf you don't want to specify each failure case, you can simplify it by using the `onFailure` extension:\n\n```kotlin\nval response = disneyService.fetchDisneyPosterList()\nresponse.onSuccess {\n    // this scope will be executed if the request successful.\n    // handle the success case\n  }.onFailure {\n      \n  }\n```\n\n#### ApiResponse Extensions With Coroutines\n\nWith the `ApiResponse` type, you can leverage [Coroutines](https://kotlinlang.org/docs/coroutines-overview.html) 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:\n\n- **suspendOnSuccess**: This extension runs if the `ApiResponse` is of type `ApiResponse.Success`. You can access the body data directly within this scope.\n\n- **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.\n\n- **suspendOnException**: If the `ApiResponse` is of type `ApiResponse.Failure.Exception`, this extension is triggered. You can access the exception message in this scope.\n\n- **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.\n\nEach extension scope operates based on the corresponding `ApiResponse` type. By utilizing these extensions, you can handle responses effectively within different coroutine contexts.\n\n```kotlin\nflow {\n  val response = disneyService.fetchDisneyPosterList()\n  response.suspendOnSuccess {\n    posterDao.insertPosterList(data) // insertPosterList(data) is a suspend function.\n    emit(data)\n  }.suspendOnError {\n    // handles error cases\n  }.suspendOnException {\n    // handles exceptional cases\n  }\n}.flowOn(Dispatchers.IO)\n```\n\n#### Flow\n\nSandwich offers some useful extensions to transform your `ApiResponse` into a [Flow](https://kotlinlang.org/docs/flow.html) by using the `toFlow` extension:\n\n```kotlin\nval flow = disneyService.fetchDisneyPosterList()\n  .onError {\n    // handles error cases when the API request gets an error response.\n  }.onException {\n    // handles exceptional cases when the API request gets an exception response.\n  }.toFlow() // returns a coroutines flow\n  .flowOn(Dispatchers.IO)\n```\n\nIf 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:\n\n```kotlin\nval response = pokedexClient.fetchPokemonList(page = page)\nresponse.toFlow { pokemons -\u003e\n  pokemons.forEach { pokemon -\u003e pokemon.page = page }\n  pokemonDao.insertPokemonList(pokemons)\n  pokemonDao.getAllPokemonList(page)\n}.flowOn(Dispatchers.IO)\n```\n\n### Retrieving\n\nSandwich provides effortless methods to directly extract the encapsulated body data from the `ApiResponse`. You can take advantage of the following functionalities:\n\n#### getOrNull\nReturns the encapsulated data if this instance represents `ApiResponse.Success` or returns null if this is failed.\n\n```kotlin\nval data: List\u003cPoster\u003e? = disneyService.fetchDisneyPosterList().getOrNull()\n```\n\n#### getOrElse\nReturns the encapsulated data if this instance represents `ApiResponse.Success` or returns a default value if this is failed.\n\n```kotlin\nval data: List\u003cPoster\u003e = disneyService.fetchDisneyPosterList().getOrElse(emptyList())\n```\n\n#### getOrThrow\nReturns the encapsulated data if this instance represents `ApiResponse.Success` or throws the encapsulated `Throwable` exception if this is failed.\n\n```kotlin\ntry {\n  val data: List\u003cPoster\u003e = disneyService.fetchDisneyPosterList().getOrThrow()\n} catch (e: Exception) {\n  e.printStackTrace()\n}\n```\n\n### Retry\n\nSandwich 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:\n\n```kotlin\nval retryPolicy = object : RetryPolicy {\n  override fun shouldRetry(attempt: Int, message: String?): Boolean = attempt \u003c= 3\n\n  override fun retryTimeout(attempt: Int, message: String?): Int = 3000\n}\n\nval apiResponse = runAndRetry(retryPolicy) { attempt, reason -\u003e\n  mainRepository.fetchPosters()\n}.onSuccess {\n  // Handle a success case\n}.onFailure {\n  // Handle failure cases\n}\n```\nThis 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.\n\n### Sequential\n\nSandwich provides sequential solutions for scenarios where you require sequential execution of network requests.\n\n#### then and suspendThen\n\nIf 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:\n\n```kotlin\nservice.getUserToken(id) suspendThen { tokenResponse -\u003e\n    service.getUserDetails(tokenResponse.token) \n} suspendThen { userResponse -\u003e\n    service.queryPosters(userResponse.user.name)\n}.mapSuccess { posterResponse -\u003e\n  posterResponse.posters\n}.onSuccess {\n    posterStateFlow.value = data\n}.onFailure {\n    Log.e(\"sequential\", message())\n}\n```\n\n### Operator\n\nThe **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.\n\nYou can streamline the handling of `onSuccess`, `onError`, and `onException` scenarios by utilizing the `operator` extension alongside the `ApiResponseOperator`. **Operator** proves particularly valuable when you're aiming for global handling of `ApiResponse` instances and wish to minimize boilerplate code within your `ViewModel` and `Repository` classes. Here are a few illustrative examples:\n\n```kotlin\n/** A common response operator for handling [ApiResponse]s regardless of its type. */\nclass CommonResponseOperator\u003cT\u003e(\n  private val success: suspend (ApiResponse.Success\u003cT\u003e) -\u003e Unit\n) : ApiResponseOperator\u003cT\u003e() {\n\n  // handles error cases when the API request gets an error response.\n  override fun onSuccess(apiResponse: ApiResponse.Success\u003cT\u003e) = success(apiResponse)\n\n  // handles error cases depending on the status code.\n  // e.g., internal server error.\n  override fun onError(apiResponse: ApiResponse.Failure.Error) {\n    apiResponse.run {\n      Timber.d(message())\n      \n      // map the ApiResponse.Failure.Error to a customized error model using the mapper.\n      map(ErrorEnvelopeMapper) {\n        Timber.d(\"[Code: $code]: $message\")\n      }\n    }\n  }\n\n  // handles exceptional cases when the API request gets an exception response.\n  // e.g., network connection error, timeout.\n  override fun onException(apiResponse: ApiResponse.Failure.Exception) {\n    apiResponse.run {\n      Timber.d(message())\n    }\n  }\n}\n\ndisneyService.fetchDisneyPosterList().operator(\n    CommonResponseOperator(\n      success = {\n        emit(data)\n        Timber.d(\"success data: $data\")\n     }\n    )\n)\n```\n\nBy 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.\n\n#### Operator With Coroutines\n\nFor 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:\n\n```kotlin\nclass CommonResponseOperator\u003cT\u003e(\n  private val success: suspend (ApiResponse.Success\u003cT\u003e) -\u003e Unit\n) : ApiResponseSuspendOperator\u003cT\u003e() {\n\n  // handles the success case when the API request gets a successful response.\n  override suspend fun onSuccess(apiResponse: ApiResponse.Success\u003cT\u003e) = success(apiResponse)\n\n  // ... //\n}\n```\n\nYou can use suspend functions like `emit` in the `success` scope.\n\n```kotlin\nval response = disneyService.fetchDisneyPosterList().suspendOperator(\n    CommonResponseOperator(\n      success = {\n        emit(data)\n        Timber.d(\"success data: $data\")\n      }\n    )\n)\n```\n\nIncorporating 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.\n\n#### Global Operator\n\nThe 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:\n\n##### Initialize Global Operator\n\nFirst, it's highly recommended to initialize the global operator in the Application class or using another initialization solution like [App Startup](https://developer.android.com/topic/libraries/app-startup). This ensures that the global operator is set up before any API requests are made.\n\n```kotlin\nclass SandwichDemoApp : Application() {\n\n  override fun onCreate() {\n    super.onCreate()\n    \n    // We will handle only the error and exceptional cases,\n    // so we don't need to mind the generic type of the operator.\n    SandwichInitializer.sandwichOperators += listOf(TokenRefreshGlobalOperator\u003cAny\u003e(this))\n\n    // ... //\n  }\n}\n```\n\nBy 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.\n\n##### Implement Your Global Operator\n\nCreate 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.\n\n```kotlin\nclass TokenRefreshGlobalOperator\u003cT\u003e @Inject constructor(\n  private val context: Context,\n  private val authService: AuthService,\n  private val userDataStore: UserDataStore,\n  coroutineScope: CoroutineScope,\n) : ApiResponseSuspendOperator\u003cT\u003e() {\n\n  private var userToken: UserToken? = null\n\n  init {\n    coroutineScope.launch {\n      userDataStore.tokenFlow.collect { token -\u003e\n        userToken = token\n      }\n    }\n  }\n\n  override suspend fun onError(apiResponse: ApiResponse.Failure.Error) {\n    // verify whether the current request was previously issued as an authenticated request\n    apiResponse.headers[\"Authorization\"] ?: return\n\n    // refresh an access token if the error response is Unauthorized or Forbidden\n    when (apiResponse.statusCode) {\n      StatusCode.Unauthorized, StatusCode.Forbidden -\u003e {\n        userToken?.let { token -\u003e\n          val result = authService.refreshToken(token)\n          result.onSuccessSuspend { data -\u003e\n            userDataStore.updateToken(\n              UserToken(\n                accessToken = data.accessToken,\n                refreshToken = data.refreshToken,\n              ),\n            )\n            toast(R.string.toast_refresh_token_succeed)\n          }.onFailureSuspend {\n            toast(R.string.toast_refresh_token_failed)\n          }\n        }\n      }\n      else -\u003e Unit\n    }\n  }\n\n  override suspend fun onSuccess(apiResponse: ApiResponse.Success\u003cT\u003e) = Unit\n\n  override suspend fun onException(apiResponse: ApiResponse.Failure.Exception) = Unit\n\n  private suspend fun toast(@StringRes resource: Int) = withContext(Dispatchers.Main) {\n    Toast.makeText(context, resource, Toast.LENGTH_SHORT).show()\n  }\n}\n```\n\nIn 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.\n\n#### Global Operator With Hilt and App Startup\n\nIf you want to initialize the global operator by using with [Hilt](https://dagger.dev/hilt/) and [App Startup](https://developer.android.com/topic/libraries/app-startup), you can follow the instructions below.\n\n\n##### 1. Implement an Entry Point\n\nFirst, you should implement an entry point for injecting the global operator into an App Startup initializer.\n\n```kotlin\n@EntryPoint\n@InstallIn(SingletonComponent::class)\ninterface NetworkEntryPoint {\n\n  fun inject(networkInitializer: NetworkInitializer)\n\n  companion object {\n\n    fun resolve(context: Context): NetworkEntryPoint {\n      val appContext = context.applicationContext ?: throw IllegalStateException(\n        \"applicationContext was not found in NetworkEntryPoint\",\n      )\n      return EntryPointAccessors.fromApplication(\n        appContext,\n        NetworkEntryPoint::class.java,\n      )\n    }\n  }\n}\n```\n\n##### 2. Provide Global Operator Dependency\n\nNext, provide your global operator with Hilt like the exambple below:\n\n```kotlin\n@Module\n@InstallIn(SingletonComponent::class)\nobject NetworkModule {\n\n  @Provides\n  @Singleton\n  fun provideTokenRefreshGlobalOperator(\n    @ApplicationContext context: Context,\n    authService: AuthService,\n    userDataStore: UserDataStore\n  ): TokenRefreshGlobalOperator\u003cAny\u003e {\n    return TokenRefreshGlobalOperator(\n      context = context,\n      authService = authService,\n      userDataStore = userDataStore,\n      coroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.IO),\n    )\n  }\n}\n```\n\n##### 3. Implement App Startup Initializer\n\nFinally, implement the App Startup Initializer and initialize the Initializer following the [App Startup guidance](https://developer.android.com/topic/libraries/app-startup#manual).\n\n```kotlin\npublic class NetworkInitializer : Initializer\u003cUnit\u003e {\n\n  @set:Inject\n  internal lateinit var tokenRefreshGlobalOperator: TokenRefreshGlobalOperator\u003cAny\u003e\n\n  override fun create(context: Context) {\n    NetworkEntryPoint.resolve(context).inject(this)\n\n    SandwichInitializer.sandwichOperators += listOf(tokenRefreshGlobalOperator)\n  }\n\n  override fun dependencies(): List\u003cClass\u003cout Initializer\u003c*\u003e\u003e\u003e = emptyList()\n}\n```\n\n\n## Find this library useful? :heart:\nSupport it by joining __[stargazers](https://github.com/skydoves/sandwich/stargazers)__ for this repository. :star: \u003cbr\u003e\nAnd __[follow](https://github.com/skydoves)__ me for my next creations! 🤩\n\n# License\n```xml\nCopyright 2020 skydoves (Jaewoong Eum)\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n   http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fskydoves%2Fsandwich","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fskydoves%2Fsandwich","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fskydoves%2Fsandwich/lists"}