diff --git a/coroutines/src/commonMain/kotlin/dev/inmo/micro_utils/coroutines/Actor.kt b/coroutines/src/commonMain/kotlin/dev/inmo/micro_utils/coroutines/Actor.kt new file mode 100644 index 00000000000..310d67c32f1 --- /dev/null +++ b/coroutines/src/commonMain/kotlin/dev/inmo/micro_utils/coroutines/Actor.kt @@ -0,0 +1,19 @@ +package dev.inmo.micro_utils.coroutines + +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.channels.Channel +import kotlinx.coroutines.launch + +fun CoroutineScope.actor( + channelCapacity: Int = Channel.UNLIMITED, + block: suspend (T) -> Unit +): Channel { + val channel = Channel(channelCapacity) + launch { + for (data in channel) { + block(data) + } + } + return channel +} + diff --git a/coroutines/src/commonMain/kotlin/dev/inmo/micro_utils/coroutines/BroadcastFlow.kt b/coroutines/src/commonMain/kotlin/dev/inmo/micro_utils/coroutines/BroadcastFlow.kt new file mode 100644 index 00000000000..d3ff5b0b277 --- /dev/null +++ b/coroutines/src/commonMain/kotlin/dev/inmo/micro_utils/coroutines/BroadcastFlow.kt @@ -0,0 +1,21 @@ +package dev.inmo.micro_utils.coroutines + +import kotlinx.coroutines.channels.* +import kotlinx.coroutines.flow.* + +@Suppress("FunctionName") +fun BroadcastFlow( + internalChannelSize: Int = Channel.BUFFERED +): BroadcastFlow { + val channel = BroadcastChannel(internalChannelSize) + + return BroadcastFlow( + channel, + channel.asFlow() + ) +} + +class BroadcastFlow internal constructor( + private val channel: BroadcastChannel, + private val flow: Flow +): Flow by flow, SendChannel by channel diff --git a/coroutines/src/commonMain/kotlin/dev/inmo/micro_utils/coroutines/DoOutsideOfCoroutine.kt b/coroutines/src/commonMain/kotlin/dev/inmo/micro_utils/coroutines/DoOutsideOfCoroutine.kt new file mode 100644 index 00000000000..a4a7e2b912b --- /dev/null +++ b/coroutines/src/commonMain/kotlin/dev/inmo/micro_utils/coroutines/DoOutsideOfCoroutine.kt @@ -0,0 +1,15 @@ +package dev.inmo.micro_utils.coroutines + +import kotlin.coroutines.* + +/** + * Call this method in case you need to do something in common thread (like reading of file in JVM) + */ +suspend fun doOutsideOfCoroutine(block: () -> T): T = suspendCoroutine { + try { + it.resume(block()) + } catch (e: Throwable) { + it.resumeWithException(e) + } +} +