簡體   English   中英

Android Firebase:如果OnCompleteListener在主應用程序線程上調用,它將如何異步工作?

[英]Android Firebase: How is OnCompleteListener working asynchronously if it called on main application thread?

我已經編寫了使用Firebase Auth創建新帳戶的代碼:

public static int signUp(String email, String password) {
  mAuth.createUserWithEmailAndPassword(email, password)
      .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
        @Override
        public void onComplete(@NonNull Task<AuthResult> task) {
          if (task.isSuccessful()) {
            Log.i("accountMessage", "User has registered successfully!");
          } else {
            try {
              throw task.getException();
            } catch (FirebaseAuthUserCollisionException e) {
              Log.i("accountMessage", "User is registered already!");
            } catch (Exception e) {
              e.printStackTrace();
            }
          }
        }
      });

  Log.i("accountMessage", "I want that this message works lastest!");
}

我可以使用LogCat捕獲accountMessage 通常,我首先必須看到"User is registered already!" 訊息,但我先看不到: Android LogCat帳戶消息 我已經在Android的Google API上看到OnCompleteListener在主應用程序線程上調用了,但是我不明白,如果OnCompleteListener在主應用程序線程上調用(我知道主應用程序線程是Android上的同一UI線程),它是如何異步工作的? 如果它在主應用程序線程上運行,是否應該同步工作? 我的意思是我們不應該首先看到"User is registered already!" ,然后顯示"I want that this message works lastest!" 信息? 如果OnCompleteListener是否異步工作,是否有一種方法可以在UI線程上同步工作?


編輯2:

實際上, onComplete的異步操作會導致以下代碼中的res[0]signUp方法返回,然后在onComplete為其賦值:

public static int signUp(String email, String password) {
  final int[] res = new int[1];
  mAuth.createUserWithEmailAndPassword(email, password)
      .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
        @Override
        public void onComplete(@NonNull Task<AuthResult> task) {
          if (task.isSuccessful()) {

            res[0] = 123;

            // We can't use 'return 123;' in here...

          }
        }
      });

  // You can see that value of res[0] is "0", because not given "123" value.
  // Must be: First, given "123" value to res[0], after then return res[0];
  return res[0];
}

該工作發生在主線程之外,因此不會阻塞您的應用程序。 然后將onComplete回調調度到主線程上,以便您無需親自進行上下文切換就可以更新UI。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM