Skip to content

Commit

Permalink
Add extension functions suspendSafeResult and toSafeResult (#47)
Browse files Browse the repository at this point in the history
  • Loading branch information
ksharma-xyz authored Sep 18, 2024
1 parent 12fb207 commit d4168a3
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,28 @@ suspend fun <T, R> T.safeResult(
Result.failure(e)
}
}

/**
* Safely runs a suspendable block on the given dispatcher.
*
* Returns a [Result] indicating success or failure.
*
* **Note:** This function will not catch [CancellationException].
*
* @param dispatcher The [CoroutineDispatcher] on which to execute the suspend block.
* @param block The suspendable block of code to execute, which returns a [Result].
* @return A [Result] object containing the success or failure of the block execution.
*
*/
suspend fun <T, R> T.suspendSafeResult(
dispatcher: CoroutineDispatcher,
block: suspend T.() -> Result<R>
): Result<R> = withContext(dispatcher) {
try {
block()
} catch (e: Throwable) {
// Should not catch CancellationException
coroutineContext.ensureActive()
Result.failure(e)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package xyz.ksharma.krail.network

import retrofit2.Response

/**
* Processes a Retrofit response and returns a [Result] object.
*
* If the response is successful, the body is extracted and wrapped in a [Result.success].
* If the response is unsuccessful, an [Exception] is created with the error code and wrapped in a [Result.failure].
*
* @return A [Result] object containing the response body or an error.
*/
fun <T> Response<T>.toSafeResult(): Result<T> {
return if (this.isSuccessful) {
this.body()?.let { body ->
Result.success(body)
} ?: Result.failure(Exception("Response body is null"))
} else {
Result.failure(Exception("API call failed with error: ${this.code()}"))
}
}

0 comments on commit d4168a3

Please sign in to comment.