Skip to content

Instantly share code, notes, and snippets.

@Pinaki93
Last active August 28, 2023 12:23
Show Gist options
  • Save Pinaki93/b33d581cad16b1c19bf1f97c15943d62 to your computer and use it in GitHub Desktop.
Save Pinaki93/b33d581cad16b1c19bf1f97c15943d62 to your computer and use it in GitHub Desktop.
An extension function to convert an RxJava2 single to a coroutine
suspend fun <T> Single<T>.suspendSubscribe(): T {
return suspendCancellableCoroutine { continuation ->
val disposable = this.subscribe({ value ->
if (continuation.isActive) {
continuation.resume(value)
}
}, { throwable ->
if (continuation.isActive) {
continuation.resumeWithException(throwable)
}
})
continuation.invokeOnCancellation {
disposable.dispose()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment