Move runCatchingExceptCancel to datasource

This commit is contained in:
Kirill Kamakin
2022-10-29 19:31:02 +02:00
parent 5c5bfdedd3
commit 6280445a7c
14 changed files with 30 additions and 25 deletions

View File

@@ -0,0 +1,15 @@
package gq.kirmanak.mealient.datasource
import kotlinx.coroutines.CancellationException
/**
* Like [runCatching] but rethrows [CancellationException] to support
* cancellation of coroutines.
*/
inline fun <T> runCatchingExceptCancel(block: () -> T): Result<T> = try {
Result.success(block())
} catch (e: CancellationException) {
throw e
} catch (e: Throwable) {
Result.failure(e)
}

View File

@@ -1,6 +1,7 @@
package gq.kirmanak.mealient.datasource.v0
import gq.kirmanak.mealient.datasource.NetworkError
import gq.kirmanak.mealient.datasource.runCatchingExceptCancel
import gq.kirmanak.mealient.datasource.v0.models.*
import gq.kirmanak.mealient.logging.Logger
import kotlinx.serialization.ExperimentalSerializationApi
@@ -80,7 +81,7 @@ class MealieDataSourceV0Impl @Inject constructor(
crossinline logParameters: () -> String,
): Result<T> {
logger.v { "${logMethod()} called with: ${logParameters()}" }
return mealieServiceV0.runCatching { block() }
return runCatchingExceptCancel { mealieServiceV0.block() }
.onFailure { logger.e(it) { "${logMethod()} request failed with: ${logParameters()}" } }
.onSuccess { logger.d { "${logMethod()} request succeeded with ${logParameters()}" } }
}

View File

@@ -1,6 +1,7 @@
package gq.kirmanak.mealient.datasource.v1
import gq.kirmanak.mealient.datasource.NetworkError
import gq.kirmanak.mealient.datasource.runCatchingExceptCancel
import gq.kirmanak.mealient.datasource.v0.models.AddRecipeRequestV0
import gq.kirmanak.mealient.datasource.v1.models.GetRecipeResponseV1
import gq.kirmanak.mealient.datasource.v1.models.GetRecipeSummaryResponseV1
@@ -72,7 +73,7 @@ class MealieDataSourceV1Impl @Inject constructor(
crossinline logParameters: () -> String,
): Result<T> {
logger.v { "${logMethod()} called with: ${logParameters()}" }
return mealieService.runCatching { block() }
return runCatchingExceptCancel { mealieService.block() }
.onFailure { logger.e(it) { "${logMethod()} request failed with: ${logParameters()}" } }
.onSuccess { logger.d { "${logMethod()} request succeeded with ${logParameters()}" } }
}