commonMain.com.github.insanusmokrassar.TelegramBotAPI.extensions.utils.FlowsAggregation.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of TelegramBotAPI-extensions-utils-js Show documentation
Show all versions of TelegramBotAPI-extensions-utils-js Show documentation
Util extensions for more useful work with updates and other things
The newest version!
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
*/
fun aggregateFlows(
withScope: CoroutineScope,
vararg flows: Flow,
internalBufferSize: Int = Channel.BUFFERED
): Flow {
val bc = BroadcastChannel(internalBufferSize)
flows.forEach {
it.onEach {
safely { bc.send(it) }
}.launchIn(withScope)
}
return bc.asFlow()
}
fun Flow>.flatMap(): Flow = flow {
collect {
it.forEach {
emit(it)
}
}
}
fun Flow.flatMap(mapper: (T) -> Iterable): Flow = flow {
collect {
mapper(it).forEach {
emit(it)
}
}
}