안드로이드
네트워크 Response 처리 라이브러리
bacass
2022. 4. 19. 15:47

안드로이드에서 주로 Retrofit2 를 이용해 네트워크를 구현하게 됩니다.
이때, API의 호출결과로 정상적이라면 200이 내려올것이고, 정상적이지 않다면 400, 404, 406, 500 등 다양한 Response가 올 수 있습니다.
Response 처리를 도와주는 라이브러리가 있어서 소개합니다.
Sandwich는 Retrofit Response를 모델링하고 예외를 처리하기 위한 API 라이브러리입니다.
https://github.com/skydoves/sandwich
GitHub - skydoves/sandwich: 🥪 A lightweight sealed API library for modeling Retrofit responses and handling exceptions.
🥪 A lightweight sealed API library for modeling Retrofit responses and handling exceptions. - GitHub - skydoves/sandwich: 🥪 A lightweight sealed API library for modeling Retrofit responses and ha...
github.com
#준비하기
build.gradle 에 라이브러리를 사용하기 위해서 sandwich를 추가한 후 sync now를 눌러줍니다.
allprojects {
repositories {
mavenCentral()
}
}
dependencies {
implementation "com.github.skydoves:sandwich:1.2.4"
}
#사용해보기
제가 예전에 만들어뒀던 샘플 프로젝트에 Sandwich를 적용해보겠습니다.
Retrofit 설정에 .addCallAdapterFactory(ApiResponseCallAdapterFactory.create()) 를 추가해줍니다.
Retrofit.Builder()
.baseUrl(BuildConfig.SERVER_HTTP_URL)
.client(OkHttpClient.Builder().apply {
connectTimeout(30, TimeUnit.SECONDS)
writeTimeout(30, TimeUnit.SECONDS)
readTimeout(30, TimeUnit.SECONDS)
addInterceptor(AddCookieInterceptor())
addInterceptor(ReceivedCookieInterceptor())
}.build())
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(ApiResponseCallAdapterFactory.create())
.build().create()
API interface 에는 ApiResponse로 받을 수 있도록 해줍니다.
interface NetworkService {
// 이미지 검색
@GET("api/")
suspend fun searchImage(
@Query("key") key: String,
@Query("q") q: String,
@Query("image_type") image_type: String,
@Query("page") page: Int,
@Query("per_page") per_page: Int
): ApiResponse<ImageObj>
}
ApiResponse 는 3가지 타입을 갖고있습니다.
Success, Failure.Error, Failure.Exception

API를 호출해봅니다.
val response = repository.searchImage(params)
response.onSuccess {
// handles the success case when the API request gets a successful response.
if (this.response.body()?.hits!!.isEmpty()) {
searchResultEvent.sendEvent(SearchResult.Fail(""))
} else {
imageListData = this.response.body()?.hits
searchResultEvent.sendEvent(SearchResult.Success)
}
}.onError {
// handles error cases when the API request gets an error response.
searchResultEvent.sendEvent(SearchResult.NetworkError)
}.onException {
// handles exceptional cases when the API request gets an exception response.
this.exception.printStackTrace()
}
#소감
예제가 매우 심플한편이라 복잡한 Response는 테스트해보지 못했습니다.
하지만 사용해보니 기존에 사용하던 Response코드보다 훨씬 간단하게 처리가 가능했습니다.
다음에 기회가 있다면 회사 업무 프로젝트에 Sandwich를 이용해보도록 해야겠습니다.