Skip to content

Instantly share code, notes, and snippets.

@sajjadjaved01
Last active March 31, 2021 12:01
Show Gist options
  • Save sajjadjaved01/d4fb49b4f5b8a2753685535f1159aa7b to your computer and use it in GitHub Desktop.
Save sajjadjaved01/d4fb49b4f5b8a2753685535f1159aa7b to your computer and use it in GitHub Desktop.
Handle API States
sealed class State<T> {
class Loading<T> : State<T>()
data class Success<T>(val data: T) : State<T>()
data class Error<T>(val message: String) : State<T>()
companion object {
/**
* Returns [State.Loading] instance.
*/
fun <T> loading() = Loading<T>()
/**
* Returns [State.Success] instance.
* @param data Data to emit with status.
*/
fun <T> success(data: T) = Success(data)
/**
* Returns [State.Error] instance.
* @param message Description of failure.
*/
fun <T> error(message: String) = Error<T>(message)
}
}
inline fun <reified T> State<T>.doIfSuccess(callback: (value: T) -> Unit) {
if (this is State.Success) {
callback(data)
}
}
inline fun <reified T> State<T>.doIfFailure(callback: (error: String?, throwable: Throwable?) -> Unit) {
if (this is State.Error) {
callback(message, throwable)
}
}
// Mapping Result
inline fun <reified T, reified R> State<T>.map(transform: (T) -> R) : State<R> {
return when(this) {
is State.Success -> State.Success(transform(data))
is State.Error -> this
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment