1
0
mirror of https://github.com/InsanusMokrassar/TelegramBotAPI.git synced 2024-06-18 07:45:27 +00:00
tgbotapi/TelegramBotAPI-extensions-utils/src/commonMain/kotlin/com/github/insanusmokrassar/TelegramBotAPI/extensions/utils/FlowsAggregation.kt

40 lines
972 B
Kotlin
Raw Normal View History

2020-08-10 05:53:54 +00:00
package com.github.insanusmokrassar.TelegramBotAPI.extensions.utils
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.channels.BroadcastChannel
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.*
/**
* Analog of [merge] function for [Flow]s. The difference is in the usage of [BroadcastChannel] in this case
*/
2020-08-10 05:53:54 +00:00
fun <T> aggregateFlows(
withScope: CoroutineScope,
vararg flows: Flow<T>,
internalBufferSize: Int = Channel.BUFFERED
): Flow<T> {
val bc = BroadcastChannel<T>(internalBufferSize)
flows.forEach {
it.onEach {
safely { bc.send(it) }
}.launchIn(withScope)
}
return bc.asFlow()
}
fun <T> Flow<Iterable<T>>.flatMap(): Flow<T> = flow {
collect {
it.forEach {
emit(it)
}
}
}
fun <T, R> Flow<T>.flatMap(mapper: (T) -> Iterable<R>): Flow<R> = flow {
collect {
mapper(it).forEach {
emit(it)
}
}
}