Skip to content

Instantly share code, notes, and snippets.

@pantos27
Created January 21, 2021 14:42
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 pantos27/dcfd753bf0a35a46ed90445ce85d79b6 to your computer and use it in GitHub Desktop.
Save pantos27/dcfd753bf0a35a46ed90445ce85d79b6 to your computer and use it in GitHub Desktop.
UI state class based on this answer https://stackoverflow.com/a/63824909/6301831
viewModel.viewState.observe(viewLifecycleOwner) { state ->
state takeIfSuccess {
// Here's the success state
} takeIfError {
// Here's the error state
}
}
sealed class UIState<out T> where T : Any? {
object Loading : UIState<Nothing>()
data class Success<T>(val data: T) : UIState<T>()
data class Failure(val errorMessage: String, val messageType: UIComponentType) : UIState<Nothing>()
}
infix fun <T> UIState<T>.takeIfSuccess(onSuccess: UIState.Success<T>.() -> Unit): UIState<T> {
return when (this) {
is UIState.Success -> {
onSuccess(this)
this
}
else -> {
this
}
}
}
infix fun <T> UIState<T>.takeIfError(onError: UIState.Failure.() -> Unit): UIState<T> {
return when (this) {
is UIState.Failure -> {
onError(this)
this
}
else -> {
this
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment