MicroUtils/coroutines/src/commonMain/kotlin/dev/inmo/micro_utils/coroutines/FlowFlatten.kt

40 lines
966 B
Kotlin
Raw Normal View History

2022-09-23 06:33:00 +00:00
package dev.inmo.micro_utils.coroutines
import kotlinx.coroutines.flow.*
2022-09-23 06:41:07 +00:00
import kotlin.js.JsName
import kotlin.jvm.JvmName
2022-09-23 06:33:00 +00:00
inline fun <T, R> Flow<Flow<T>>.flatMap(
crossinline mapper: suspend (T) -> R
) = flow {
collect {
it.collect {
emit(mapper(it))
}
}
}
2022-09-23 06:41:07 +00:00
@JsName("flatMapIterable")
@JvmName("flatMapIterable")
2022-09-23 06:33:00 +00:00
inline fun <T, R> Flow<Iterable<T>>.flatMap(
crossinline mapper: suspend (T) -> R
) = map {
it.asFlow()
}.flatMap(mapper)
inline fun <T, R> Flow<Flow<T>>.flatMapNotNull(
crossinline mapper: suspend (T) -> R
2022-09-23 06:41:07 +00:00
) = flatMap(mapper).takeNotNull()
2022-09-23 06:33:00 +00:00
2022-09-23 06:41:07 +00:00
@JsName("flatMapNotNullIterable")
@JvmName("flatMapNotNullIterable")
2022-09-23 06:33:00 +00:00
inline fun <T, R> Flow<Iterable<T>>.flatMapNotNull(
crossinline mapper: suspend (T) -> R
2022-09-23 06:41:07 +00:00
) = flatMap(mapper).takeNotNull()
2022-09-23 06:33:00 +00:00
fun <T> Flow<Flow<T>>.flatten() = flatMap { it }
2022-09-23 06:41:07 +00:00
@JsName("flattenIterable")
@JvmName("flattenIterable")
fun <T> Flow<Iterable<T>>.flatten() = flatMap { it }