add Flow#subscribe

This commit is contained in:
InsanusMokrassar 2020-11-01 00:54:07 +06:00
parent 7f19b83828
commit b690f68c7f
2 changed files with 41 additions and 0 deletions

View File

@ -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

View File

@ -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 <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,
noinline onException: ExceptionHandler<Unit> = { 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 <T> Flow<T>.subscribeSafelyWithoutExceptions(
scope: CoroutineScope,
noinline block: suspend (T) -> Unit
) = subscribeSafely(
scope,
{},
block
)