Last active
August 28, 2023 12:23
-
-
Save Pinaki93/b33d581cad16b1c19bf1f97c15943d62 to your computer and use it in GitHub Desktop.
An extension function to convert an RxJava2 single to a coroutine
This file contains 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
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