我正面临 tasks现在,我有疑问。电子邮件/通行证注册后,我必须更新用户的个人资料。所以我首先尝试了这个:
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!
问题出在最后一行,我的监听器等待 AuthResult
参数,但 updateProfile
任务发送了一个 Void
。我像下面那样处理了这种情况,但它似乎太乱了。告诉我是否还有其他更好的方法:
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);
最佳答案
您似乎希望将 AuthResult 直接传递给 mOnSignInSuccessListener。在这种特殊情况下,在我看来,尝试强制执行额外的 Continuation 以返回您正在寻找的值是不值得的。
与其尝试安排将 AuthResult 作为参数传递给该监听器,监听器可以直接访问 mainTask.getResult(),或者您可以将 AuthResult 保存在成员变量中并以这种方式访问它。无论哪种方式,它都是安全的,因为 mOnSignInSuccessListener 只会在 mainTask 完成后调用,这确保了 AuthResult 准备就绪。
关于android - 当给定参数不同时如何正确地继续任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40161374/