'Completable.create of RXJava equivalent in Kotlin Coroutines- Android
I am working on Firebase authentication wherein I need to put the firebase auth on my Repository. I found this article on how to do it but it uses RxJava. (https://www.simplifiedcoding.net/firebase-mvvm-example/)
Now, I want to know if there's a kotlin only solution for this since I dont want to use RxJava because I'm using kotlin coroutines.
fun facebookLogin(credential: AuthCredential) = Completable.create { emitter -> // change Completable.create since it is a RxJava
firebaseAuth.signInWithCredential(credential).addOnCompleteListener { task ->
if (!emitter.isDisposed) {
if (task.isSuccessful)
emitter.onComplete()
else
emitter.onError(task.exception!!)
}
}
}
Solution 1:[1]
Continuation allows you to transform something synchronous into asynchronous
There used to be something about this on the official coroutine codelab but they seem to have removed it. The boilerplate goes roughly like this:
suspend fun facebookLogin(...): Boolean {
return suspendCoroutine { continuation ->
firebaseAuth.signInWithCredential(credential).addOnCompleteListener { task ->
if (task.isSuccessful)
continuation.resume(true)
else
continuation.resumeWith(Result.failure(task.exception))
}
}
}
}
And to invoke it from a ViewModel you would
fun login () {
viewModelScope.launch{
facebookLogin(...)
}
}
If not on view model, you can always
CoroutineContext(Dispatchers.IO).launch{
facebookLogin(...)
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | melbic |