Better impl of runSuspendCatching

This commit is contained in:
tarsin committed 2023-02-08 22:38:18 +08:00
1 parent 899d221b67
commit 461ad7fa42
2 files changed
+11 -18

No files matched your search

@@ -22,7 +22,7 @@ import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.Semaphore
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.sync.withPermit
import moe.tarsin.coroutines.runCatchingCancellationTransparent
import moe.tarsin.coroutines.runSuspendCatching
import kotlin.coroutines.CoroutineContext
class SpiderQueenWorker(private val queen: SpiderQueen) : CoroutineScope {
@@ -148,7 +148,7 @@ class SpiderQueenWorker(private val queen: SpiderQueen) : CoroutineScope {
"?nl=$skipHathKey"
}
}
runCatchingCancellationTransparent {
runSuspendCatching {
getGalleryPage(pageUrl, spiderInfo.gid, spiderInfo.token).also {
if (StringUtils.endsWith(it.imageUrl, URL_509_SUFFIX_ARRAY)) {
// Get 509
@@ -193,7 +193,7 @@ class SpiderQueenWorker(private val queen: SpiderQueen) : CoroutineScope {
error = "ShowKey error"
return@repeat
}
runCatchingCancellationTransparent {
runSuspendCatching {
getGalleryPageApi(
spiderInfo.gid,
index,
@@ -239,7 +239,7 @@ class SpiderQueenWorker(private val queen: SpiderQueen) : CoroutineScope {
}
Log.d(DEBUG_TAG, targetImageUrl)
runCatchingCancellationTransparent {
runSuspendCatching {
Log.d(DEBUG_TAG, "Start download image $index")
val success: Boolean = spiderDen.makeHttpCallAndSaveImage(
index,
@@ -2,20 +2,13 @@ package moe.tarsin.coroutines
import kotlinx.coroutines.CancellationException
inline fun <R> runCatchingCancellationTransparent(block: () -> R): Result<R> {
return try {
Result.success(block())
} catch (e: Throwable) {
if (e is CancellationException) throw e
Result.failure(e)
}
inline fun <reified T : Throwable> Result<*>.except(): Result<*> =
onFailure { if (it is T) throw it }
inline fun <R> runSuspendCatching(block: () -> R): Result<R> {
return runCatching(block).apply { except<CancellationException>() }
}
inline fun <T, R> T.runCatchingCancellationTransparent(block: T.() -> R): Result<R> {
return try {
Result.success(block())
} catch (e: Throwable) {
if (e is CancellationException) throw e
Result.failure(e)
}
inline fun <T, R> T.runSuspendCatching(block: T.() -> R): Result<R> {
return runCatching(block).apply { except<CancellationException>() }
}