cuddlecheek cuddlecheek -4 years ago 194
Android Question

Android firebase auth synchronous sign in

When we want code to run after sign in to firebase, we use

addOnCompleteListener
like this:

void signInToFirebaseUsing(GoogleSignInAccount googleAccount) {
AuthCredential credential = GoogleAuthProvider.getCredential(googleAccount.getIdToken(), null)
firebaseAuth.signInWithCredential(credential)
.addOnCompleteListener { ...
if (task.isSuccessful()) {
...
} else {
...
}
}
}


However, firebase isn't the only service I want to sign in. I need a synchronous firebase sign in so I could handle multiple authentications like this (I use Kotlin with AsyncAwait library, but you get the idea):

private fun signInToAppUsing(googleAccount: GoogleSignInAccount) {
async {
try {
await { signInToRealmUsing(googleAccount) }
await { signInToFirebaseUsing(googleAccount) } // <- this won't work because firebase uses asynchronous listener
// User is signed in all services
} catch (e: Exception) {
// Signing in some service crashed
}
}
}


Is there a way to do this?

Answer Source

Firebase API wasn't designed to expose blocking work synchronous, it exposes blocking work as a Task to be listened to.

So, you can manage your own objects to maintain a record of the state of all the async work you want to track for completion. Then, when the last thing finishes, proceed with whatever logic you want.

As you know, Play services (and Firebase) provides Task objects that let you listen for success or failure. If you convert all your async work to trigger their own Task objects to completion using TaskCompletionSource, and collect all the Tasks you want to wait for, you can then listen to the result of the aggregate collection of Tasks with Tasks.whenAll().

The fourth part of my blog series about Tasks covers this.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download