How to properly continue tasks when a given parameter is different

烂漫一生 提交于 2019-12-24 10:50:02

问题


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);

回答1:


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.



来源:https://stackoverflow.com/questions/40161374/how-to-properly-continue-tasks-when-a-given-parameter-is-different

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!