Last active
April 29, 2019 04:52
-
-
Save mataku/bf185338081f5ff065498742fbe0ec27 to your computer and use it in GitHub Desktop.
This file contains 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
class ApiErrorHandler(val context: Context?) { | |
fun handle(throwable: Throwable) { | |
// レスポンスコードとエラーレスポンスの中身をパースしてユーザにエラー内容を伝えるためのなにかをする | |
if (throwable is HttpException) { | |
... | |
} | |
} | |
} |
This file contains 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
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) | |
} |
This file contains 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
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 | |
} | |
} |
This file contains 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
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