From b7934cf357b250b01c1fcf532c63295a64d97efc Mon Sep 17 00:00:00 2001 From: InsanusMokrassar Date: Fri, 23 Sep 2022 12:33:00 +0600 Subject: [PATCH] flows extensions --- CHANGELOG.md | 3 ++ .../micro_utils/coroutines/FlowFlatten.kt | 31 +++++++++++++++++++ 2 files changed, 34 insertions(+) create mode 100644 coroutines/src/commonMain/kotlin/dev/inmo/micro_utils/coroutines/FlowFlatten.kt diff --git a/CHANGELOG.md b/CHANGELOG.md index 3b90c01aaba..69d4ee6307f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,9 @@ ## 0.12.15 +* `Coroutines`: + * Add `Flow` extensions `flatMap` and `flatten` + ## 0.12.14 * `Versions`: diff --git a/coroutines/src/commonMain/kotlin/dev/inmo/micro_utils/coroutines/FlowFlatten.kt b/coroutines/src/commonMain/kotlin/dev/inmo/micro_utils/coroutines/FlowFlatten.kt new file mode 100644 index 00000000000..095ebd3573d --- /dev/null +++ b/coroutines/src/commonMain/kotlin/dev/inmo/micro_utils/coroutines/FlowFlatten.kt @@ -0,0 +1,31 @@ +package dev.inmo.micro_utils.coroutines + +import kotlinx.coroutines.flow.* + +inline fun Flow>.flatMap( + crossinline mapper: suspend (T) -> R +) = flow { + collect { + it.collect { + emit(mapper(it)) + } + } +} + +inline fun Flow>.flatMap( + crossinline mapper: suspend (T) -> R +) = map { + it.asFlow() +}.flatMap(mapper) + +inline fun Flow>.flatMapNotNull( + crossinline mapper: suspend (T) -> R +) = flatMap(mapper).filterNot { it == null } + +inline fun Flow>.flatMapNotNull( + crossinline mapper: suspend (T) -> R +) = flatMap(mapper).filterNot { it == null } + +fun Flow>.flatten() = flatMap { it } + +fun Flow>.flatten() = flatMap { it }