Skip to content

Instantly share code, notes, and snippets.

@NikolaDespotoski
Created April 12, 2022 00:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NikolaDespotoski/3ece222240a851bf00c210739193fc34 to your computer and use it in GitHub Desktop.
Save NikolaDespotoski/3ece222240a851bf00c210739193fc34 to your computer and use it in GitHub Desktop.
cancelWhen operator for Kotlin Flow
/**
* 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