All Downloads are FREE. Search and download functionalities are using the official Maven repository.

commonMain.pro.respawn.flowmvi.modules.Recoverable.kt Maven / Gradle / Ivy

Go to download

A Kotlin Multiplatform MVI library based on plugins that is simple, fast, powerful & flexible

There is a newer version: 3.0.0
Show newest version
package pro.respawn.flowmvi.modules

import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.launch
import pro.respawn.flowmvi.api.DelicateStoreApi
import pro.respawn.flowmvi.api.MVIAction
import pro.respawn.flowmvi.api.MVIIntent
import pro.respawn.flowmvi.api.MVIState
import pro.respawn.flowmvi.api.PipelineContext
import pro.respawn.flowmvi.api.Recoverable

@OptIn(DelicateStoreApi::class)
@Suppress("FunctionName")
internal fun  Recoverable.PipelineExceptionHandler(
    pipeline: PipelineContext,
) = CoroutineExceptionHandler { ctx, e ->
    when {
        e !is Exception -> throw e
        ctx[Recoverable] != null -> throw e
        // add Recoverable to the coroutine context
        // and handle the exception asynchronously to allow suspending inside recover
        else -> with(pipeline) { launch(this@PipelineExceptionHandler) { recover(e) } }
    }
}

@DelicateStoreApi
internal suspend inline fun  Recoverable.catch(
    ctx: PipelineContext,
    block: () -> Unit
) = try {
    block()
} catch (e: CancellationException) {
    throw e
} catch (expected: Exception) {
    with(ctx) { recover(expected) }
}