Created
April 12, 2022 00:00
-
-
Save NikolaDespotoski/3ece222240a851bf00c210739193fc34 to your computer and use it in GitHub Desktop.
cancelWhen operator for Kotlin Flow
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Cancels current flow when the predicate is matched, throws [CancellationException] up in | |
* current coroutine. | |
* @param cause class that will be used as cause for [CancellationException] | |
* @param predicate if result of this function is [true] then the flow is stopped | |
*/ | |
inline fun <T> Flow<T>.cancelWhen( | |
cause: KClass<out Throwable>? = null, | |
crossinline predicate: (T) -> Boolean | |
): Flow<T> = transform { | |
if (!predicate(it)) { | |
emit(it) | |
return@transform | |
} | |
currentCoroutineContext().cancel( | |
CancellationException( | |
message = "Cancelling flow on predicate match for value: $it", | |
cause = cause?.java?.newInstance() | |
) | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment