Last active
January 25, 2019 02:16
-
-
Save AdamMc331/ea57ef6f0889bdca28337ac950e46879 to your computer and use it in GitHub Desktop.
Shows a way to use function types to handle errors.
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
// Create a custom error class that holds both the error that occured, | |
// and a function to invoke if it retries. | |
data class MyCustomError( | |
val error: Throwable? = null, | |
val retry: (() -> Unit)? = null | |
) | |
// Create a state class that represents the current state of your screen. | |
// This is where you'd wanna put data you have to display, like a list of items | |
// or maybe an error, and a function to call if you want to retry something | |
data class MyState( | |
val data: List<Item>? = null, | |
val error: MyCustomError? = null | |
) | |
class MyPresenter : MyContract.Presenter { | |
private var view: MyContract.View = //... | |
private var currentState = MyState() | |
fun loadData() { | |
myFlowable | |
.subscribeOn(Schedulers.io()) | |
.observeOn(AndroidSchedulers.mainThread()) | |
.subscribe( | |
{ result -> | |
val newState = MyState(data = result.data) | |
handleState(newState) | |
}, | |
{ error -> | |
val retry = { this.loadData() } // This is how you define a function type in Kotlin | |
val myError = MyCustomError(error, retry) | |
val newState = MyState(error = myError) | |
handleState(newState) | |
} | |
) | |
} | |
// Somewhere in the view, after you show the error, you'll probably have a button click | |
// that would call this method | |
fun retryButtonClicked() { | |
currentState.error?.retry?.invoke() | |
} | |
private fun handleState(newState: MyState) { | |
currentState = newState | |
if (currentState.data != null) { | |
myView.showItems(currentState.data) | |
} | |
if (currentState.error != null) { | |
myView.showError(currentState.error) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment