From c96143d23d1681c72e4adfc23c287ea43f90de18 Mon Sep 17 00:00:00 2001 From: Nek-12 Date: Mon, 11 Dec 2023 15:59:14 +0300 Subject: [PATCH] add `rethrow` operator --- .../kotlin/pro/respawn/apiresult/ApiResult.kt | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/core/src/commonMain/kotlin/pro/respawn/apiresult/ApiResult.kt b/core/src/commonMain/kotlin/pro/respawn/apiresult/ApiResult.kt index de3f811..0905d7e 100644 --- a/core/src/commonMain/kotlin/pro/respawn/apiresult/ApiResult.kt +++ b/core/src/commonMain/kotlin/pro/respawn/apiresult/ApiResult.kt @@ -24,9 +24,8 @@ import kotlin.jvm.JvmName /** * A class that represents a result of an operation. - * Create an instance with [ApiResult.invoke] and use various operators on the resulting object. * - * This class is **extremely efficient**: no actual objects are created, + * This class is **efficient**: no actual objects are created unless dynamic type resolution is required, * all operations are inlined and no function resolution is performed. * ApiResult is **not** an Rx-style callback chain - * the operators that are invoked are called **immediately** and in-place. @@ -61,7 +60,6 @@ public sealed interface ApiResult { */ public operator fun not(): T = orThrow() - /** * A value of [ApiResult] for its successful state. * @param result a successful result value @@ -97,10 +95,14 @@ public sealed interface ApiResult { */ public val isLoading: Boolean get() = this is Loading + /** + * A loading state of an [ApiResult] + */ public companion object Loading : ApiResult { + override fun equals(other: Any?): Boolean = other is Loading + override fun hashCode(): Int = 42 override fun toString(): String = "ApiResult.Loading" - override fun equals(other: Any?): Boolean = other === Loading /** * Execute [call], catching any exceptions, and wrap it in an [ApiResult]. @@ -204,6 +206,13 @@ public inline fun ApiResult.orThrow(): T = when (this) { is Success -> result } +/** + * Throws if [this] result is an [Error] and [Error.e] is of type [T]. Ignores all other exceptions. + * + * @return a result that can be [Error] but is guaranteed to not have an exception of type [T] wrapped. + */ +public inline fun ApiResult.rethrow(): ApiResult = mapError { throw it } + /** * Fold [this] returning the result of [onSuccess] or [onError] * By default, maps [Loading] to [Error] with [NotFinishedException]