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

53 lines
1.6 KiB
Kotlin
Raw Normal View History

2020-10-31 18:54:07 +00:00
@file:Suppress("NOTHING_TO_INLINE")
package dev.inmo.micro_utils.coroutines
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.*
2021-06-25 18:46:51 +00:00
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
2020-10-31 18:54:07 +00:00
/**
* Shortcut for chain if [Flow.onEach] and [Flow.launchIn]
*/
inline fun <T> Flow<T>.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 <T> Flow<T>.subscribeSafely(
scope: CoroutineScope,
2020-12-22 09:42:11 +00:00
noinline onException: ExceptionHandler<Unit> = defaultSafelyExceptionHandler,
2020-10-31 18:54:07 +00:00
noinline block: suspend (T) -> Unit
) = subscribe(scope) {
safely(onException) {
block(it)
}
}
/**
2021-03-29 11:57:36 +00:00
* Use [subscribeSafelyWithoutExceptions], but all exceptions will be passed to [defaultSafelyExceptionHandler]
2020-10-31 18:54:07 +00:00
*/
inline fun <T> Flow<T>.subscribeSafelyWithoutExceptions(
scope: CoroutineScope,
2021-06-25 18:46:51 +00:00
noinline onException: ExceptionHandler<T?> = defaultSafelyWithoutExceptionHandlerWithNull,
2020-10-31 18:54:07 +00:00
noinline block: suspend (T) -> Unit
2021-03-29 11:57:36 +00:00
) = subscribe(scope) {
2021-06-25 18:46:51 +00:00
safelyWithoutExceptions(onException) {
2021-03-29 11:57:36 +00:00
block(it)
}
}
/**
* Use [subscribeSafelyWithoutExceptions], but all exceptions inside of [safely] will be skipped
*/
inline fun <T> Flow<T>.subscribeSafelySkippingExceptions(
scope: CoroutineScope,
noinline block: suspend (T) -> Unit
) = subscribe(scope) {
safelyWithoutExceptions({ /* skip exceptions */ }) {
block(it)
}
}