Created
June 24, 2018 09:55
-
-
Save TomoyaShibata/965901bf95c9348f926fcb622020453e to your computer and use it in GitHub Desktop.
Retrofit2、RxJava2 でエラー時のレスポンスをいい感じに Data Class に詰める
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.tomoyashibata.myapplication | |
data class ErrorMessage( | |
val message: String, | |
val errors: List<Error> | |
) | |
data class Error( | |
val resource: String, | |
val field: String, | |
val code: String | |
) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.tomoyashibata.myapplication | |
import io.reactivex.Single | |
import retrofit2.http.GET | |
interface GitHubService { | |
// クエリパラメータ `q` が必須だがエラーハンドリングの確認のためにわざと取り除いている | |
@GET("/search/users") | |
fun searchUsers(): Single<Users> | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// コア部分だけ抜粋 | |
package com.tomoyashibata.myapplication | |
import com.squareup.moshi.Moshi | |
import io.reactivex.android.schedulers.AndroidSchedulers | |
import io.reactivex.schedulers.Schedulers | |
import retrofit2.Retrofit | |
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory | |
import retrofit2.converter.moshi.MoshiConverterFactory | |
import timber.log.Timber | |
import com.squareup.moshi.JsonAdapter | |
import retrofit2.HttpException | |
fun searchUsers(): Unit { | |
service.searchUsers() | |
.subscribeOn(Schedulers.io()) | |
.observeOn(AndroidSchedulers.mainThread()) | |
.subscribe({ | |
Timber.i("success!!") | |
Timber.i(it.toString()) | |
}, { | |
Timber.i("error!!") | |
if (it is HttpException) { | |
val adapter = Moshi.Builder().build().adapter(ErrorMessage::class.java) | |
val errorMessage = adapter.fromJson(it.response().errorBody()?.string()) | |
Timber.e(errorMessage.toString()) | |
} | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment