add coroutines utils

This commit is contained in:
InsanusMokrassar 2020-09-26 22:08:39 +06:00
parent 29b3e6b701
commit dd3b9f3674
3 changed files with 55 additions and 0 deletions

View File

@ -0,0 +1,19 @@
package dev.inmo.micro_utils.coroutines
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.launch
fun <T> CoroutineScope.actor(
channelCapacity: Int = Channel.UNLIMITED,
block: suspend (T) -> Unit
): Channel<T> {
val channel = Channel<T>(channelCapacity)
launch {
for (data in channel) {
block(data)
}
}
return channel
}

View File

@ -0,0 +1,21 @@
package dev.inmo.micro_utils.coroutines
import kotlinx.coroutines.channels.*
import kotlinx.coroutines.flow.*
@Suppress("FunctionName")
fun <T> BroadcastFlow(
internalChannelSize: Int = Channel.BUFFERED
): BroadcastFlow<T> {
val channel = BroadcastChannel<T>(internalChannelSize)
return BroadcastFlow(
channel,
channel.asFlow()
)
}
class BroadcastFlow<T> internal constructor(
private val channel: BroadcastChannel<T>,
private val flow: Flow<T>
): Flow<T> by flow, SendChannel<T> by channel

View File

@ -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 <T> doOutsideOfCoroutine(block: () -> T): T = suspendCoroutine {
try {
it.resume(block())
} catch (e: Throwable) {
it.resumeWithException(e)
}
}