Skip to content

Instantly share code, notes, and snippets.

@mataku
Last active April 29, 2019 04:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mataku/bf185338081f5ff065498742fbe0ec27 to your computer and use it in GitHub Desktop.
Save mataku/bf185338081f5ff065498742fbe0ec27 to your computer and use it in GitHub Desktop.
class ApiErrorHandler(val context: Context?) {
fun handle(throwable: Throwable) {
// レスポンスコードとエラーレスポンスの中身をパースしてユーザにエラー内容を伝えるためのなにかをする
if (throwable is HttpException) {
...
}
}
}
class ExamplePresenter(val view: ExampleView, val repository: UserRepository) {
fun fetchName() {
repository
.fetchName()
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ result ->
result
.onSuccess {
view.showName(it)
}
.onFailure {
view.showError(it)
}
})
...
}
}
interface ExampleView {
fun showName(name: String)
fun showError(throwable: Throwable)
}
sealed class ExampleResult<T> {
data class Success<T>(val data: T) : ExampleResult<T>()
data class Failure<T>(val throwable: Throwable) : ExampleResult<T>()
inline fun <T> ExampleResult<T>.onFailure(action: (exception: Throwable) -> Unit): ExampleResult<T> {
if (this is ExampleResult.Failure) {
action(it)
}
return this
}
inline fun <T> ExampleResult<T>.onSuccess(action: (value: T) -> Unit): ExampleResult<T> {
if (this is ExampleResult.Success) {
action(this.data)
}
return this
}
}
import io.reactivex.Single
class UserRepository {
// Single<Result<表示に必要な型>> を返す
fun fetchName() : Single<ExampleResult<String>> {
ApiClient().create(UsersService::class.java)
.fetchName()
.map {
val body = it.body()
if (it.isSuccessful && body != null) {
ExampleResult.success(body.name)
} else {
ExampleResult.failure(HttpException(it))
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment