mirror of
https://github.com/InsanusMokrassar/MicroUtils.git
synced 2025-09-04 23:59:29 +00:00
several more addings
This commit is contained in:
@@ -0,0 +1,33 @@
|
||||
package dev.inmo.micro_utils.coroutines
|
||||
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.channels.BroadcastChannel
|
||||
import kotlinx.coroutines.channels.Channel
|
||||
import kotlinx.coroutines.flow.*
|
||||
|
||||
class BroadcastStateFlow<T> internal constructor(
|
||||
parentFlow: Flow<T>,
|
||||
private val stateGetter: () -> T
|
||||
) : StateFlow<T>, Flow<T> by parentFlow {
|
||||
override val value: T
|
||||
get() = stateGetter()
|
||||
}
|
||||
|
||||
fun <T> BroadcastChannel<T>.asStateFlow(value: T, scope: CoroutineScope): StateFlow<T> = asFlow().let {
|
||||
var state: T = value
|
||||
it.onEach { state = it }.launchIn(scope)
|
||||
BroadcastStateFlow(it) {
|
||||
state
|
||||
}
|
||||
}
|
||||
|
||||
fun <T> BroadcastChannel<T?>.asStateFlow(scope: CoroutineScope): StateFlow<T?> = asStateFlow(null, scope)
|
||||
|
||||
fun <T> broadcastStateFlow(initial: T, scope: CoroutineScope, channelSize: Int = Channel.BUFFERED) = BroadcastChannel<T>(
|
||||
channelSize
|
||||
).let {
|
||||
it to it.asStateFlow(initial, scope)
|
||||
}
|
||||
|
||||
fun <T> broadcastStateFlow(scope: CoroutineScope, channelSize: Int = Channel.BUFFERED) = broadcastStateFlow<T?>(null, scope, channelSize)
|
||||
|
@@ -0,0 +1,7 @@
|
||||
package dev.inmo.micro_utils.coroutines
|
||||
|
||||
import kotlinx.coroutines.CompletableDeferred
|
||||
import kotlinx.coroutines.Deferred
|
||||
|
||||
val <T> T.asDeferred: Deferred<T>
|
||||
get() = CompletableDeferred(this)
|
Reference in New Issue
Block a user