Created
August 31, 2023 21:23
-
-
Save tim4dev/3fe0cf7ab36ff468fd4a96ba61b420a7 to your computer and use it in GitHub Desktop.
UiState
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
/* | |
* 2021 Yuriy Timofeev <[email protected]>. | |
*/ | |
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