Java Code Examples for com.google.android.gms.tasks.Task#continueWithTask()

The following examples show how to use com.google.android.gms.tasks.Task#continueWithTask() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: StorageReference.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * List all items (files) and prefixes (folders) under this StorageReference.
 *
 * <p>This is a helper method for calling {@code list()} repeatedly until there are no more
 * results. Consistency of the result is not guaranteed if objects are inserted or removed while
 * this operation is executing.
 *
 * <p>{@code listAll()} is only available for projects using <a
 * href="https://firebase.google.com/docs/rules/rules-behavior#security_rules_version_2">Firebase
 * Rules Version 2</a>.
 *
 * @throws OutOfMemoryError If there are too many items at this location.
 * @return A {@link Task} that returns all items and prefixes under the current StorageReference.
 */
@NonNull
public Task<ListResult> listAll() {
  TaskCompletionSource<ListResult> pendingResult = new TaskCompletionSource<>();

  List<StorageReference> prefixes = new ArrayList<>();
  List<StorageReference> items = new ArrayList<>();

  Executor executor = StorageTaskScheduler.getInstance().getCommandPoolExecutor();
  Task<ListResult> list = listHelper(/* maxResults= */ null, /* pageToken= */ null);

  Continuation<ListResult, Task<Void>> continuation =
      new Continuation<ListResult, Task<Void>>() {
        @Override
        public Task<Void> then(@NonNull Task<ListResult> currentPage) {
          if (currentPage.isSuccessful()) {
            ListResult result = currentPage.getResult();
            prefixes.addAll(result.getPrefixes());
            items.addAll(result.getItems());

            if (result.getPageToken() != null) {
              Task<ListResult> nextPage =
                  listHelper(/* maxResults= */ null, result.getPageToken());
              nextPage.continueWithTask(executor, this);
            } else {
              pendingResult.setResult(new ListResult(prefixes, items, /* pageToken= */ null));
            }
          } else {
            pendingResult.setException(currentPage.getException());
          }

          return Tasks.forResult(null);
        }
      };

  list.continueWithTask(executor, continuation);

  return pendingResult.getTask();
}
 
Example 2
Source File: FirebaseAuthCredentialsProvider.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@Override
public synchronized Task<String> getToken() {
  boolean doForceRefresh = forceRefresh;
  forceRefresh = false;
  Task<GetTokenResult> res = authProvider.getAccessToken(doForceRefresh);

  // Take note of the current value of the tokenCounter so that this method can fail (with a
  // FirebaseFirestoreException) if there is a token change while the request is outstanding.
  final int savedCounter = tokenCounter;
  return res.continueWithTask(
      Executors.DIRECT_EXECUTOR,
      task -> {
        synchronized (this) {
          // Cancel the request since the token changed while the request was outstanding so the
          // response is potentially for a previous user (which user, we can't be sure).
          if (savedCounter != tokenCounter) {
            Logger.debug(LOG_TAG, "getToken aborted due to token change");
            return getToken();
          }

          if (task.isSuccessful()) {
            return Tasks.forResult(task.getResult().getToken());
          } else {
            return Tasks.forException(task.getException());
          }
        }
      });
}
 
Example 3
Source File: MainActivity.java    From android-samples with Apache License 2.0 5 votes vote down vote up
private <T> Task<Void> updateUiAfterTask(Task<T> task) {
    Task<Void> loadFolderTask = task.continueWithTask(task1 -> {
        DriveFolder currentFolder = mNavigationPath.peek().asDriveFolder();
        return loadFolderNameAndContents(currentFolder);
    });
    // Wait till Metadata is loaded to allow user interaction.
    loadFolderTask.addOnCompleteListener(task12 -> setUiInteractionsEnabled(true));
    return loadFolderTask;
}
 
Example 4
Source File: ConfigFetchHandler.java    From firebase-android-sdk with Apache License 2.0 4 votes vote down vote up
/**
 * Fetches from the backend if the fetched configs cache has expired and the client is not
 * currently throttled.
 *
 * <p>If a fetch request is made to the backend, updates the last fetch status, last successful
 * fetch time and {@link BackoffMetadata} in {@link ConfigMetadataClient}.
 */
private Task<FetchResponse> fetchIfCacheExpiredAndNotThrottled(
    Task<ConfigContainer> cachedFetchConfigsTask, long minimumFetchIntervalInSeconds) {
  Date currentTime = new Date(clock.currentTimeMillis());
  if (cachedFetchConfigsTask.isSuccessful()
      && areCachedFetchConfigsValid(minimumFetchIntervalInSeconds, currentTime)) {
    // Keep the cached fetch values if the cache has not expired yet.
    return Tasks.forResult(FetchResponse.forLocalStorageUsed(currentTime));
  }

  Task<FetchResponse> fetchResponseTask;

  Date backoffEndTime = getBackoffEndTimeInMillis(currentTime);
  if (backoffEndTime != null) {
    // TODO(issues/260): Provide a way for users to check for throttled status so exceptions
    // aren't the only way for users to determine if they're throttled.
    fetchResponseTask =
        Tasks.forException(
            new FirebaseRemoteConfigFetchThrottledException(
                createThrottledMessage(backoffEndTime.getTime() - currentTime.getTime()),
                backoffEndTime.getTime()));
  } else {
    Task<String> installationIdTask = firebaseInstallations.getId();
    Task<InstallationTokenResult> installationAuthTokenTask =
        firebaseInstallations.getToken(false);
    fetchResponseTask =
        Tasks.whenAllComplete(installationIdTask, installationAuthTokenTask)
            .continueWithTask(
                executor,
                (completedInstallationsTasks) -> {
                  if (!installationIdTask.isSuccessful()) {
                    return Tasks.forException(
                        new FirebaseRemoteConfigClientException(
                            "Firebase Installations failed to get installation ID for fetch.",
                            installationIdTask.getException()));
                  }

                  if (!installationAuthTokenTask.isSuccessful()) {
                    return Tasks.forException(
                        new FirebaseRemoteConfigClientException(
                            "Firebase Installations failed to get installation auth token for fetch.",
                            installationAuthTokenTask.getException()));
                  }

                  String installationId = installationIdTask.getResult();
                  String installationToken = installationAuthTokenTask.getResult().getToken();
                  return fetchFromBackendAndCacheResponse(
                      installationId, installationToken, currentTime);
                });
  }

  return fetchResponseTask.continueWithTask(
      executor,
      (completedFetchTask) -> {
        updateLastFetchStatusAndTime(completedFetchTask, currentTime);
        return completedFetchTask;
      });
}