From be52871de863c94f6f7dbd278a3c0d2f7b4ae9ae Mon Sep 17 00:00:00 2001 From: InsanusMokrassar Date: Fri, 23 Sep 2022 12:41:07 +0600 Subject: [PATCH] flows extensions --- CHANGELOG.md | 3 ++- .../inmo/micro_utils/coroutines/FlowFlatten.kt | 16 ++++++++++++---- .../inmo/micro_utils/coroutines/FlowNullables.kt | 6 ++++++ 3 files changed, 20 insertions(+), 5 deletions(-) create mode 100644 coroutines/src/commonMain/kotlin/dev/inmo/micro_utils/coroutines/FlowNullables.kt diff --git a/CHANGELOG.md b/CHANGELOG.md index 69d4ee6307f..aba0a1b17b4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,7 +3,8 @@ ## 0.12.15 * `Coroutines`: - * Add `Flow` extensions `flatMap` and `flatten` + * Add `Flow` extensions `flatMap`, `flatMapNotNull` and `flatten` + * Add `Flow` extensions `takeNotNull` and `filterNotNull` ## 0.12.14 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 index 095ebd3573d..6e5c6d4b729 100644 --- a/coroutines/src/commonMain/kotlin/dev/inmo/micro_utils/coroutines/FlowFlatten.kt +++ b/coroutines/src/commonMain/kotlin/dev/inmo/micro_utils/coroutines/FlowFlatten.kt @@ -1,6 +1,8 @@ package dev.inmo.micro_utils.coroutines import kotlinx.coroutines.flow.* +import kotlin.js.JsName +import kotlin.jvm.JvmName inline fun Flow>.flatMap( crossinline mapper: suspend (T) -> R @@ -12,6 +14,8 @@ inline fun Flow>.flatMap( } } +@JsName("flatMapIterable") +@JvmName("flatMapIterable") inline fun Flow>.flatMap( crossinline mapper: suspend (T) -> R ) = map { @@ -20,12 +24,16 @@ inline fun Flow>.flatMap( inline fun Flow>.flatMapNotNull( crossinline mapper: suspend (T) -> R -) = flatMap(mapper).filterNot { it == null } +) = flatMap(mapper).takeNotNull() +@JsName("flatMapNotNullIterable") +@JvmName("flatMapNotNullIterable") inline fun Flow>.flatMapNotNull( crossinline mapper: suspend (T) -> R -) = flatMap(mapper).filterNot { it == null } - -fun Flow>.flatten() = flatMap { it } +) = flatMap(mapper).takeNotNull() fun Flow>.flatten() = flatMap { it } + +@JsName("flattenIterable") +@JvmName("flattenIterable") +fun Flow>.flatten() = flatMap { it } diff --git a/coroutines/src/commonMain/kotlin/dev/inmo/micro_utils/coroutines/FlowNullables.kt b/coroutines/src/commonMain/kotlin/dev/inmo/micro_utils/coroutines/FlowNullables.kt new file mode 100644 index 00000000000..e6b665e47f3 --- /dev/null +++ b/coroutines/src/commonMain/kotlin/dev/inmo/micro_utils/coroutines/FlowNullables.kt @@ -0,0 +1,6 @@ +package dev.inmo.micro_utils.coroutines + +import kotlinx.coroutines.flow.* + +fun Flow.takeNotNull() = mapNotNull { it } +fun Flow.filterNotNull() = takeNotNull()