Fabricio Fabricio - 1 month ago 19
Android Question

How to properly continue tasks when a given parameter is different

I'm facing tasks right now and I have doubts. After an email/pass registration, I had to update the user's profile. So I first tried this:

FirebaseAuth.getInstance().createUserWithEmailAndPassword(email, password);
.continueWithTask(new Continuation<AuthResult, Task<Void>>() {
@Override
public Task<Void> then(@NonNull Task<AuthResult> t) throws Exception {
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setDisplayName(fullname)
.build();
return t.getResult().getUser().updateProfile(profileUpdates);
}
})
.addOnFailureListener(this, mOnSignInFailureListener)
.addOnSuccessListener(this, mOnSignInSuccessListener); // <- problem!


The problem is in the last line my listener waits for an
AuthResult
parameter but
updateProfile
task sends a
Void
. I handled that situation like bellow but it seems too messy. Tell me if there is another better way to do this:

final Task<AuthResult> mainTask;
mainTask = FirebaseAuth.getInstance().createUserWithEmailAndPassword(email, password);
mainTask
.continueWithTask(new Continuation<AuthResult, Task<Void>>() {
@Override
public Task<Void> then(@NonNull Task<AuthResult> t) throws Exception {
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setDisplayName(fullname)
.build();
return t.getResult().getUser().updateProfile(profileUpdates);
}
})
.continueWithTask(new Continuation<Void, Task<AuthResult>>() {
@Override
public Task<AuthResult> then(@NonNull Task<Void> t) throws Exception {
return mainTask;
}
})
.addOnFailureListener(this, mOnSignInFailureListener)
.addOnSuccessListener(this, mOnSignInSuccessListener);

Answer

It looks like you're expecting an AuthResult to get passed directly to mOnSignInSuccessListener. In this particular case, in my opinion, it's not worthwhile to try to coerce an extra Continuation to return the value you're looking for.

Instead of trying to arrange for the AuthResult to be passed to that listener as a parameter, the listener can simply reach directly into mainTask.getResult(), or you can save the AuthResult in a member variable and access it that way. Either way, it's safe because the mOnSignInSuccessListener will only be invoked after mainTask completes, which ensures the AuthResult is ready.