Skip to content

Instantly share code, notes, and snippets.

@tim4dev
Created August 31, 2023 21:23
Show Gist options
  • Save tim4dev/3fe0cf7ab36ff468fd4a96ba61b420a7 to your computer and use it in GitHub Desktop.
Save tim4dev/3fe0cf7ab36ff468fd4a96ba61b420a7 to your computer and use it in GitHub Desktop.
UiState
/*
* 2021 Yuriy Timofeev <intelligence.worker@gmail.com>.
*/
sealed class UiState<out T> where T : Any? {
object Loading : UiState<Nothing>()
data class Success<T>(val data: T) : UiState<T>()
data class Error(val message: String, val error: Throwable) : UiState<Nothing>()
fun fold(
onLoading: () -> Unit,
onSuccess: (T) -> Unit,
onError: (Error) -> Unit
) {
when (this) {
Loading -> onLoading.invoke()
is Success -> onSuccess(this.data)
is Error -> onError(this)
}
}
}
infix fun <T> UiState<T>.takeIfSuccess(onSuccess: T.() -> Unit): UiState<T> {
return when (this) {
is UiState.Success -> {
onSuccess(this.data)
this
}
else -> {
this
}
}
}
infix fun <T> UiState<T>.takeIfError(onError: UiState.Error.() -> Unit): UiState<T> {
return when (this) {
is UiState.Error -> {
onError(this)
this
}
else -> {
this
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment