Untitled
unknown
kotlin
a year ago
1.2 kB
15
Indexable
sealed interface Result<out T>
data class Success<T>(val result: T) : Result<T>
data class Error(val message: String) : Result<Nothing>
inline fun <T : DefaultResponse, R> Result<T>.mapState(transform: (T) -> R): Result<R> {
return when (this) {
is Success -> Success(transform(result))
is Error -> Error(message)
}
}
suspend fun <T> Result<T>.onSuccess(action: suspend (T) -> Unit): Result<T> {
if (this is Success) action(result)
return this
}
suspend fun <T> Result<T>.onError(action: suspend (String) -> Unit): Result<T> {
if (this is Error) action(message)
return this
}
suspend inline fun <reified T : DefaultResponse> asResult(crossinline request: suspend () -> T): Result<T> =
withContext(Dispatchers.IO) {
try {
with(request()) {
return@with when (status) {
RequestStatus.SUCCESS -> Success(this)
RequestStatus.ERROR -> Error(msg.ifEmpty { "An error occurred" })
}
}
} catch (e: Exception) {
return@withContext Error(e.message ?: "An error occurred")
}
}
Editor is loading...
Leave a Comment