Skip to content

Instantly share code, notes, and snippets.

@G00fY2
Last active November 3, 2022 12:50
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 G00fY2/c203e83e4e074cf77f412046b76c51d0 to your computer and use it in GitHub Desktop.
Save G00fY2/c203e83e4e074cf77f412046b76c51d0 to your computer and use it in GitHub Desktop.
Extension function to convert Google Play Services Tasks result to RxJava Single
import com.google.android.gms.tasks.Task
import io.reactivex.rxjava3.core.Single
import java.util.concurrent.CancellationException
import java.util.concurrent.TimeUnit
fun <T : Any> Task<T>.toSingle(): Single<T> {
return if (isComplete) {
Single.fromCallable(::asRequired)
} else {
Single.create<T> { emitter ->
addOnCompleteListener {
try {
emitter.onSuccess(it.asRequired())
} catch (e: Exception) {
emitter.onError(e)
}
}
}
}
}
private fun <T : Any> Task<T>.asRequired(): T {
return if (isComplete) {
if (!isCanceled) {
exception?.let { throw it } ?: result ?: throw IllegalStateException("Result of task $this was null")
} else {
throw CancellationException("Task $this was cancelled normally")
}
} else {
throw IllegalStateException("Task $this not complete")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment