Last active
March 31, 2021 12:01
-
-
Save sajjadjaved01/d4fb49b4f5b8a2753685535f1159aa7b to your computer and use it in GitHub Desktop.
Handle API States
This file contains 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 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