Last active
November 3, 2022 12:50
-
-
Save G00fY2/c203e83e4e074cf77f412046b76c51d0 to your computer and use it in GitHub Desktop.
Extension function to convert Google Play Services Tasks result to RxJava Single
This file contains hidden or 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
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