Skip to content

Instantly share code, notes, and snippets.

@Nillerr
Last active May 25, 2021 17:12
Show Gist options
  • Save Nillerr/5c4f76b342b7e4dde63dc644885c6bad to your computer and use it in GitHub Desktop.
Save Nillerr/5c4f76b342b7e4dde63dc644885c6bad to your computer and use it in GitHub Desktop.
AnyFlow<T> with collect
class AnyFlow<T>(source: Flow<T>): Flow<T> by source {
fun collect(onEach: (T) -> Unit, onCompletion: (cause: Throwable?) -> Unit): Cancellable {
val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
scope.launch {
try {
collect {
onEach(it)
}
onCompletion(null)
} catch (e: Throwable) {
onCompletion(e)
}
}
return object : Cancellable {
override fun cancel() {
scope.cancel()
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment