diff --git a/CHANGELOG.md b/CHANGELOG.md index ada66eaee48..94ffe51e19d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,10 @@ * `Coroutines` * `BroadcastFlow` now is deprecated * `BroadcastStateFlow` now is deprecated + * New extensions for `Flow`s: + * `Flow#subscribe` + * `Flow#subscribeSafely` + * `Flow#subscribeSafelyWithoutExceptions` ## 0.2.3 diff --git a/coroutines/src/commonMain/kotlin/dev/inmo/micro_utils/coroutines/FlowSubscription.kt b/coroutines/src/commonMain/kotlin/dev/inmo/micro_utils/coroutines/FlowSubscription.kt new file mode 100644 index 00000000000..474c230f2c0 --- /dev/null +++ b/coroutines/src/commonMain/kotlin/dev/inmo/micro_utils/coroutines/FlowSubscription.kt @@ -0,0 +1,37 @@ +@file:Suppress("NOTHING_TO_INLINE") + +package dev.inmo.micro_utils.coroutines + +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.flow.* + +/** + * Shortcut for chain if [Flow.onEach] and [Flow.launchIn] + */ +inline fun Flow.subscribe(scope: CoroutineScope, noinline block: suspend (T) -> Unit) = onEach(block).launchIn(scope) + +/** + * Use [subscribe], but all [block]s will be called inside of [safely] function. + * Use [onException] to set up your reaction for [Throwable]s + */ +inline fun Flow.subscribeSafely( + scope: CoroutineScope, + noinline onException: ExceptionHandler = { throw it }, + noinline block: suspend (T) -> Unit +) = subscribe(scope) { + safely(onException) { + block(it) + } +} + +/** + * Use [subscribeSafelyWithoutExceptions], but all exceptions inside of [safely] will be skipped + */ +inline fun Flow.subscribeSafelyWithoutExceptions( + scope: CoroutineScope, + noinline block: suspend (T) -> Unit +) = subscribeSafely( + scope, + {}, + block +)