Skip to content

Instantly share code, notes, and snippets.

@fededri
Created January 26, 2022 03:26
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 fededri/4902c7bf755ef3b3c138d810bd4a1d26 to your computer and use it in GitHub Desktop.
Save fededri/4902c7bf755ef3b3c138d810bd4a1d26 to your computer and use it in GitHub Desktop.
class FlowWrapper<T>(private val source: Flow<T>) : Flow<T> by source {
init {
freeze()
}
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