mirror of
https://github.com/InsanusMokrassar/MicroUtils.git
synced 2024-11-17 13:53:49 +00:00
add coroutines utils
This commit is contained in:
parent
29b3e6b701
commit
dd3b9f3674
@ -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
|
||||
}
|
||||
|
@ -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
|
@ -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)
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user