Created
January 21, 2021 14:42
-
-
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
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
viewModel.viewState.observe(viewLifecycleOwner) { state -> | |
state takeIfSuccess { | |
// Here's the success state | |
} takeIfError { | |
// Here's the error state | |
} | |
} |
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
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