Tasks API

從 Google Play 服務 9.0.0 版開始,您可以使用 Task API 和多種方法,傳回 Task 或其子類別。Task 是代表非同步方法呼叫的 API,類似於 Google Play 服務先前版本中的 PendingResult

處理工作結果

傳回 Task 的常用方法是 FirebaseAuth.signInAnonymously()。它會傳回 Task<AuthResult>,表示工作在成功時會傳回 AuthResult 物件:

Task<AuthResult> task = FirebaseAuth.getInstance().signInAnonymously();

如要在工作成功時收到通知,請附加 OnSuccessListener

task.addOnSuccessListener(new OnSuccessListener<AuthResult>() {
    @Override
    public void onSuccess(AuthResult authResult) {
        // Task completed successfully
        // ...
    }
});

如要接收工作失敗通知,請附加 OnFailureListener

task.addOnFailureListener(new OnFailureListener() {
    @Override
    public void onFailure(@NonNull Exception e) {
        // Task failed with an exception
        // ...
    }
});

如要在同一個事件監聽器中處理成功和失敗情況,請附加 OnCompleteListener

task.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
    @Override
    public void onComplete(@NonNull Task<AuthResult> task) {
        if (task.isSuccessful()) {
            // Task completed successfully
            AuthResult result = task.getResult();
        } else {
            // Task failed with an exception
            Exception exception = task.getException();
        }
    }
});

執行緒

根據預設,連接至執行緒的監聽器會在應用程式主 (UI) 執行緒上執行。附加事件監聽器時,您也可以指定用於排程事件監聽器的 Executor

// Create a new ThreadPoolExecutor with 2 threads for each processor on the
// device and a 60 second keep-alive time.
int numCores = Runtime.getRuntime().availableProcessors();
ThreadPoolExecutor executor = new ThreadPoolExecutor(numCores * 2, numCores *2,
        60L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());

task.addOnCompleteListener(executor, new OnCompleteListener<AuthResult>() {
    @Override
    public void onComplete(@NonNull Task<AuthResult> task) {
        // ...
    }
});

活動範圍的事件監聽器

如果您要在 Activity 中監聽工作結果,建議您在工作中加入活動範圍的事件監聽器。這些事件監聽器會在活動的 onStop 方法中移除,因此當活動不再顯示時,系統就不會呼叫事件監聽器。

Activity activity = MainActivity.this;
task.addOnCompleteListener(activity, new OnCompleteListener<AuthResult>() {
    @Override
    public void onComplete(@NonNull Task<AuthResult> task) {
        // ...
    }
});

鏈結

如果您使用多個會傳回 Task 的 API,可以使用接續項目將這些 API 串連在一起。這有助於避免深層巢狀回呼,並整合工作鏈結的錯誤處理。

舉例來說,方法 doSomething 會傳回 Task<String>,但需要 AuthResult,我們會從工作中以非同步方式取得 AuthResult

public Task<String> doSomething(AuthResult authResult) {
    // ...
}

我們可以使用 Task.continueWithTask 方法,將這兩項工作串連起來:

Task<AuthResult> signInTask = FirebaseAuth.getInstance().signInAnonymously();

signInTask.continueWithTask(new Continuation<AuthResult, Task<String>>() {
    @Override
    public Task<String> then(@NonNull Task<AuthResult> task) throws Exception {
        // Take the result from the first task and start the second one
        AuthResult result = task.getResult();
        return doSomething(result);
    }
}).addOnSuccessListener(new OnSuccessListener<String>() {
    @Override
    public void onSuccess(String s) {
        // Chain of tasks completed successfully, got result from last task.
        // ...
    }
}).addOnFailureListener(new OnFailureListener() {
    @Override
    public void onFailure(@NonNull Exception e) {
        // One of the tasks in the chain failed with an exception.
        // ...
    }
});

封鎖

如果程式已在背景執行緒中執行,您可以封鎖工作,以便同步取得結果並避免回呼:

try {
    // Block on a task and get the result synchronously. This is generally done
    // when executing a task inside a separately managed background thread. Doing this
    // on the main (UI) thread can cause your application to become unresponsive.
    AuthResult authResult = Tasks.await(task);
} catch (ExecutionException e) {
    // The Task failed, this is the same exception you'd get in a non-blocking
    // failure handler.
    // ...
} catch (InterruptedException e) {
    // An interrupt occurred while waiting for the task to complete.
    // ...
}

您也可以在封鎖工作時指定逾時值,避免應用程式停止運作:

try {
    // Block on the task for a maximum of 500 milliseconds, otherwise time out.
    AuthResult authResult = Tasks.await(task, 500, TimeUnit.MILLISECONDS);
} catch (ExecutionException e) {
    // ...
} catch (InterruptedException e) {
    // ...
} catch (TimeoutException e) {
    // Task timed out before it could complete.
    // ...
}

互通性

Task 在概念上與多種熱門 Android 方法相符,可用於管理非同步程式碼,且 Task 可直接轉換為其他基本元素,包括 ListenableFuture 和 Kotlin 協同程式,這些都是 AndroidX 建議的元素。

以下是使用 Task 的範例:

// ...
simpleTask.addOnCompleteListener(this) {
  completedTask -> textView.text = completedTask.result
}

Kotlin 協同程式

用量

將下列依附元件新增至專案,然後使用下列程式碼從 Task 轉換。

Gradle (模組層級 build.gradle,通常是 app/build.gradle)
// Source: https://github.com/Kotlin/kotlinx.coroutines/tree/master/integration/kotlinx-coroutines-play-services
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-play-services:1.7.3'
文字片段
import kotlinx.coroutines.tasks.await
// ...
  textView.text = simpleTask.await()
}

Guava ListenableFuture

將下列依附元件新增至專案,然後使用下列程式碼從 Task 轉換。

Gradle (模組層級 build.gradle,通常是 app/build.gradle)
implementation "androidx.concurrent:concurrent-futures:1.2.0"
文字片段
import com.google.common.util.concurrent.ListenableFuture
// ...
/** Convert Task to ListenableFuture. */
fun <T> taskToListenableFuture(task: Task<T>): ListenableFuture<T> {
  return CallbackToFutureAdapter.getFuture { completer ->
    task.addOnCompleteListener { completedTask ->
      if (completedTask.isCanceled) {
        completer.setCancelled()
      } else if (completedTask.isSuccessful) {
        completer.set(completedTask.result)
      } else {
        val e = completedTask.exception
        if (e != null) {
          completer.setException(e)
        } else {
          throw IllegalStateException()
        }
      }
    }
  }
}
// ...
this.listenableFuture = taskToListenableFuture(simpleTask)
this.listenableFuture?.addListener(
  Runnable {
    textView.text = listenableFuture?.get()
  },
  ContextCompat.getMainExecutor(this)
)

RxJava2 可觀察項目

除了所選的相對非同步程式庫外,請將下列依附元件新增至專案,並使用下列程式碼從 Task 轉換。

Gradle (模組層級 build.gradle,通常是 app/build.gradle)
// Source: https://github.com/ashdavies/rx-tasks
implementation 'io.ashdavies.rx.rxtasks:rx-tasks:2.2.0'
文字片段
import io.ashdavies.rx.rxtasks.toSingle
import java.util.concurrent.TimeUnit
// ...
simpleTask.toSingle(this).subscribe { result -> textView.text = result }

後續步驟