add actions actor

This commit is contained in:
InsanusMokrassar 2021-03-01 18:35:11 +06:00
parent 42594f0656
commit d933dc532b
2 changed files with 48 additions and 0 deletions

View File

@ -5,6 +5,8 @@
* `Versions`: * `Versions`:
* `Kotlin`: `1.4.30` -> `1.4.31` * `Kotlin`: `1.4.30` -> `1.4.31`
* `Ktor`: `1.5.1` -> `1.5.2` * `Ktor`: `1.5.1` -> `1.5.2`
* `Coroutines`
* Add `createActionsActor`/`createSafeActionsActor` and `doWithSuspending`
## 0.4.27 ## 0.4.27

View File

@ -0,0 +1,46 @@
package dev.inmo.micro_utils.coroutines
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.channels.Channel
import kotlin.coroutines.*
interface ActorAction<T> {
suspend operator fun invoke(): T
}
/**
* Planned to use with [doWithSuspending]. Will execute incoming lambdas sequentially
*
* @see actor
*/
fun CoroutineScope.createActionsActor() = actor<suspend () -> Unit> {
it()
}
/**
* Planned to use with [doWithSuspending]. Will execute incoming lambdas sequentially
*
* @see safeActor
*/
inline fun CoroutineScope.createSafeActionsActor(
noinline onException: ExceptionHandler<Unit> = defaultSafelyExceptionHandler
) = safeActor<suspend () -> Unit>(Channel.UNLIMITED, onException) {
it()
}
/**
* Must be use with actor created by [createActionsActor] or [createSafeActionsActor]. Will send lambda which will
* execute [action] and return result.
*
* @see suspendCoroutine
* @see safely
*/
suspend fun <T> Channel<suspend () -> Unit>.doWithSuspending(
action: ActorAction<T>
) = suspendCoroutine<T> {
offer {
safely({ e -> it.resumeWithException(e) }) {
it.resume(action())
}
}
}