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에서 작업 결과를 수신 대기하는 경우 활동 범위 리스너를 작업에 추가하는 것이 좋습니다. 이러한 리스너는 Activity의 onStop 메서드 중에 삭제되므로 Activity가 더 이상 표시되지 않을 때는 리스너가 호출되지 않습니다.

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이 필요합니다.

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 접근 방식에 부합하며, TaskAndroidX에서 권장되는 ListenableFuture와 Kotlin 코루틴을 비롯하여 다른 프리미티브로 간단하게 변환할 수 있습니다.

다음은 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.4.1'
snippet
import kotlinx.coroutines.tasks.await
// ...
  textView.text = simpleTask.await()
}

Guava ListenableFuture

프로젝트에 다음 종속 항목을 추가하고 아래 코드를 사용하여 Task에서 변환합니다.

Gradle (모듈 수준 build.gradle, 일반적으로 app/build.gradle)
implementation "androidx.concurrent:concurrent-futures:1.1.0"
snippet
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'
snippet
import io.ashdavies.rx.rxtasks.toSingle
import java.util.concurrent.TimeUnit
// ...
simpleTask.toSingle(this).subscribe { result -> textView.text = result }

다음 단계