com.google.android.gms.tasks.Continuation Java Examples

The following examples show how to use com.google.android.gms.tasks.Continuation. 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: Utils.java    From firebase-android-sdk with Apache License 2.0 7 votes vote down vote up
/** @return A tasks that is resolved when either of the given tasks is resolved. */
public static <T> Task<T> race(Task<T> t1, Task<T> t2) {
  final TaskCompletionSource<T> result = new TaskCompletionSource<>();
  Continuation<T, Void> continuation =
      new Continuation<T, Void>() {
        @Override
        public Void then(@NonNull Task<T> task) throws Exception {
          if (task.isSuccessful()) {
            result.trySetResult(task.getResult());
          } else {
            result.trySetException(task.getException());
          }
          return null;
        }
      };
  t1.continueWith(continuation);
  t2.continueWith(continuation);
  return result.getTask();
}
 
Example #2
Source File: FirebaseMultiQuery.java    From white-label-event-app with Apache License 2.0 7 votes vote down vote up
public Task<Map<DatabaseReference, DataSnapshot>> start() {
    // Create a Task<DataSnapshot> to trigger in response to each database listener.
    //
    final ArrayList<Task<DataSnapshot>> tasks = new ArrayList<>(refs.size());
    for (final DatabaseReference ref : refs) {
        final TaskCompletionSource<DataSnapshot> source = new TaskCompletionSource<>();
        final ValueEventListener listener = new MyValueEventListener(ref, source);
        ref.addListenerForSingleValueEvent(listener);
        listeners.put(ref, listener);
        tasks.add(source.getTask());
    }

    // Return a single Task that triggers when all queries are complete.  It contains
    // a map of all original DatabaseReferences originally given here to their resulting
    // DataSnapshot.
    //
    return Tasks.whenAll(tasks).continueWith(new Continuation<Void, Map<DatabaseReference, DataSnapshot>>() {
        @Override
        public Map<DatabaseReference, DataSnapshot> then(@NonNull Task<Void> task) throws Exception {
            task.getResult();
            return new HashMap<>(snaps);
        }
    });
}
 
Example #3
Source File: MainActivity.java    From quickstart-android with Apache License 2.0 6 votes vote down vote up
private Task<Integer> addNumbers(int a, int b) {
    // Create the arguments to the callable function, which are two integers
    Map<String, Object> data = new HashMap<>();
    data.put("firstNumber", a);
    data.put("secondNumber", b);

    // Call the function and extract the operation from the result
    return mFunctions
            .getHttpsCallable("addNumbers")
            .call(data)
            .continueWith(new Continuation<HttpsCallableResult, Integer>() {
                @Override
                public Integer then(@NonNull Task<HttpsCallableResult> task) throws Exception {
                    // This continuation runs on either success or failure, but if the task
                    // has failed then getResult() will throw an Exception which will be
                    // propagated down.
                    Map<String, Object> result = (Map<String, Object>) task.getResult().getData();
                    return (Integer) result.get("operationResult");
                }
            });
}
 
Example #4
Source File: MainActivity.java    From drive-android-quickstart with Apache License 2.0 6 votes vote down vote up
/** Create a new file and save it to Drive. */
private void saveFileToDrive() {
  // Start by creating a new contents, and setting a callback.
  Log.i(TAG, "Creating new contents.");
  final Bitmap image = mBitmapToSave;

  mDriveResourceClient
      .createContents()
      .continueWithTask(
          new Continuation<DriveContents, Task<Void>>() {
            @Override
            public Task<Void> then(@NonNull Task<DriveContents> task) throws Exception {
              return createFileIntentSender(task.getResult(), image);
            }
          })
      .addOnFailureListener(
          new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
              Log.w(TAG, "Failed to create new contents.", e);
            }
          });
}
 
Example #5
Source File: MainActivity.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
private void runTaskTest(
    final String testName,
    TaskProvider runner,
    final @Nullable SortedSet<Integer> inputStreamInjections,
    final @Nullable SortedSet<Integer> outputStreamInjections) {
  final Task<StringBuilder> task = runner.getTask();

  StreamProvider streamProvider =
      () -> {
        TaskCompletionSource<StreamDownloadResponse> result = new TaskCompletionSource<>();
        task.continueWith(
            AsyncTask.THREAD_POOL_EXECUTOR,
            (Continuation<StringBuilder, Object>)
                testResult -> {
                  StreamDownloadResponse response = new StreamDownloadResponse();
                  response.mainTask = testResult.getResult();
                  result.setResult(response);
                  return response;
                });
        return result.getTask();
      };

  runTaskTest(testName, streamProvider, inputStreamInjections, outputStreamInjections);
}
 
Example #6
Source File: AutoMLImageLabelerProcessor.java    From quickstart-android with Apache License 2.0 6 votes vote down vote up
@Override
protected Task<List<FirebaseVisionImageLabel>> detectInImage(final FirebaseVisionImage image) {
  if (modelDownloadingTask == null) {
    // No download task means only the locally bundled model is used. Model can be used directly.
    return detector.processImage(image);
  } else if (!modelDownloadingTask.isComplete()) {
    if (mode == Mode.LIVE_PREVIEW) {
      Log.i(TAG, "Model download is in progress. Skip detecting image.");
      return Tasks.forResult(Collections.<FirebaseVisionImageLabel>emptyList());
    } else {
      Log.i(TAG, "Model download is in progress. Waiting...");
      return modelDownloadingTask.continueWithTask(new Continuation<Void, Task<List<FirebaseVisionImageLabel>>>() {
        @Override
        public Task<List<FirebaseVisionImageLabel>> then(@NonNull Task<Void> task) {
          return processImageOnDownloadComplete(image);
        }
      });
    }
  } else {
    return processImageOnDownloadComplete(image);
  }
}
 
Example #7
Source File: MainActivity.java    From quickstart-android with Apache License 2.0 6 votes vote down vote up
private Task<String> addMessage(String text) {
    // Create the arguments to the callable function.
    Map<String, Object> data = new HashMap<>();
    data.put("text", text);
    data.put("push", true);

    return mFunctions
            .getHttpsCallable("addMessage")
            .call(data)
            .continueWith(new Continuation<HttpsCallableResult, String>() {
                @Override
                public String then(@NonNull Task<HttpsCallableResult> task) throws Exception {
                    // This continuation runs on either success or failure, but if the task
                    // has failed then getResult() will throw an Exception which will be
                    // propagated down.
                    String result = (String) task.getResult().getData();
                    return result;
                }
            });
}
 
Example #8
Source File: ProviderUtils.java    From FirebaseUI-Android with Apache License 2.0 6 votes vote down vote up
public static Task<String> fetchTopProvider(
        @NonNull FirebaseAuth auth,
        @NonNull FlowParameters params,
        @NonNull String email) {
    return fetchSortedProviders(auth, params, email)
            .continueWithTask(new Continuation<List<String>, Task<String>>() {
                @Override
                public Task<String> then(@NonNull Task<List<String>> task) {
                    if (!task.isSuccessful()) {
                        return Tasks.forException(task.getException());
                    }
                    List<String> providers = task.getResult();

                    if (providers.isEmpty()) {
                        return Tasks.forResult(null);
                    } else {
                        return Tasks.forResult(providers.get(0));
                    }
                }
            });
}
 
Example #9
Source File: SolutionCounters.java    From snippets-android with Apache License 2.0 6 votes vote down vote up
public Task<Void> createCounter(final DocumentReference ref, final int numShards) {
    // Initialize the counter document, then initialize each shard.
    return ref.set(new Counter(numShards))
            .continueWithTask(new Continuation<Void, Task<Void>>() {
                @Override
                public Task<Void> then(@NonNull Task<Void> task) throws Exception {
                    if (!task.isSuccessful()) {
                        throw task.getException();
                    }

                    List<Task<Void>> tasks = new ArrayList<>();

                    // Initialize each shard with count=0
                    for (int i = 0; i < numShards; i++) {
                        Task<Void> makeShard = ref.collection("shards")
                                .document(String.valueOf(i))
                                .set(new Shard(0));

                        tasks.add(makeShard);
                    }

                    return Tasks.whenAll(tasks);
                }
            });
}
 
Example #10
Source File: GoogleFitModule.java    From react-native-google-fitness with MIT License 6 votes vote down vote up
@ReactMethod
public void disableFit(Promise promise) {
    try {
        Fitness
                .getConfigClient(mReactContext, getLastSignedInAccountSafely())
                .disableFit()
                .continueWithTask(new Continuation<Void, Task<Void>>() {
                    @Override
                    public Task<Void> then(@NonNull Task<Void> task) throws Exception {
                        GoogleSignInOptions options = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).build();
                        return GoogleSignIn
                                .getClient(mReactContext, options)
                                .signOut();
                    }
                })
                .addOnFailureListener(new SimpleFailureListener(promise))
                .addOnSuccessListener(new SimpleSuccessListener(promise));
    } catch (Exception e) {
        promise.reject(e);
    }
}
 
Example #11
Source File: MainActivity.java    From snippets-android with Apache License 2.0 6 votes vote down vote up
public void taskChaining() {
    // [START task_chaining]
    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.
            // ...
        }
    });
    // [END task_chaining]
}
 
Example #12
Source File: AuthOperationManager.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
public Task<AuthResult> safeLink(final AuthCredential credential,
                                 final AuthCredential credentialToLink,
                                 final FlowParameters flowParameters) {
    return getScratchAuth(flowParameters)
            .signInWithCredential(credential)
            .continueWithTask(new Continuation<AuthResult, Task<AuthResult>>() {
                @Override
                public Task<AuthResult> then(@NonNull Task<AuthResult> task) throws Exception {
                    if (task.isSuccessful()) {
                        return task.getResult().getUser().linkWithCredential(credentialToLink);
                    }
                    return task;
                }
            });
}
 
Example #13
Source File: RemoteBackup.java    From Database-Backup-Restore with Apache License 2.0 5 votes vote down vote up
private Task<DriveId> pickItem(OpenFileActivityOptions openOptions) {
    mOpenItemTaskSource = new TaskCompletionSource<>();
    mDriveClient
            .newOpenFileActivityIntentSender(openOptions)
            .continueWith((Continuation<IntentSender, Void>) task -> {
                activity.startIntentSenderForResult(
                        task.getResult(), REQUEST_CODE_OPENING, null, 0, 0, 0);
                return null;
            });
    return mOpenItemTaskSource.getTask();
}
 
Example #14
Source File: ChatViewModel.java    From quickstart-android with Apache License 2.0 5 votes vote down vote up
private Task<List<SmartReplySuggestion>> generateReplies(List<Message> messages,
                                                         boolean isEmulatingRemoteUser) {
    Message lastMessage = messages.get(messages.size() - 1);

    // If the last message in the chat thread is not sent by the "other" user, don't generate
    // smart replies.
    if (lastMessage.isLocalUser && !isEmulatingRemoteUser || !lastMessage.isLocalUser && isEmulatingRemoteUser) {
        return Tasks.forException(new Exception("Not running smart reply!"));
    }

    List<FirebaseTextMessage> chatHistory = new ArrayList<>();
    for (Message message : messages) {
        if (message.isLocalUser && !isEmulatingRemoteUser || !message.isLocalUser && isEmulatingRemoteUser) {
            chatHistory.add(FirebaseTextMessage.createForLocalUser(message.text,
                    message.timestamp));
        } else {
            chatHistory.add(FirebaseTextMessage.createForRemoteUser(message.text,
                    message.timestamp, REMOTE_USER_ID));
        }
    }

    return FirebaseNaturalLanguage.getInstance().getSmartReply().suggestReplies(chatHistory)
            .continueWith(new Continuation<SmartReplySuggestionResult, List<SmartReplySuggestion>>() {
                @Override
                public List<SmartReplySuggestion> then(@NonNull Task<SmartReplySuggestionResult> task) {
                    return task.getResult().getSuggestions();
                }
            });
}
 
Example #15
Source File: SnapshotCoordinator.java    From android-basic-samples with Apache License 2.0 5 votes vote down vote up
public Task<SnapshotsClient.DataOrConflict<Snapshot>> open(final SnapshotsClient snapshotsClient,
                                                           final SnapshotMetadata snapshotMetadata,
                                                           final int conflictPolicy) {
  final String filename = snapshotMetadata.getUniqueName();

  return setIsOpeningTask(filename).continueWithTask(new Continuation<Void, Task<SnapshotsClient.DataOrConflict<Snapshot>>>() {
    @Override
    public Task<SnapshotsClient.DataOrConflict<Snapshot>> then(@NonNull Task<Void> task) throws Exception {
      return snapshotsClient.open(snapshotMetadata, conflictPolicy)
          .addOnCompleteListener(createOpenListener(filename));
    }
  });
}
 
Example #16
Source File: SnapshotCoordinator.java    From android-basic-samples with Apache License 2.0 5 votes vote down vote up
public Task<SnapshotsClient.DataOrConflict<Snapshot>> open(final SnapshotsClient snapshotsClient,
                                                           final SnapshotMetadata snapshotMetadata) {
  final String filename = snapshotMetadata.getUniqueName();

  return setIsOpeningTask(filename).continueWithTask(new Continuation<Void, Task<SnapshotsClient.DataOrConflict<Snapshot>>>() {
    @Override
    public Task<SnapshotsClient.DataOrConflict<Snapshot>> then(@NonNull Task<Void> task) throws Exception {
      return snapshotsClient.open(snapshotMetadata)
          .addOnCompleteListener(createOpenListener(filename));
    }
  });
}
 
Example #17
Source File: AutoCompleteTask.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
@NonNull
@Override
public <TContinuationResult> Task<TContinuationResult> continueWith(
        @NonNull Continuation<TResult, TContinuationResult> continuation) {
    try {
        return Tasks.forResult(continuation.then(this));
    } catch (Exception e) {
        return Tasks.forException(unwrap(e));
    }
}
 
Example #18
Source File: AutoCompleteTask.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
@NonNull
@Override
public <TContinuationResult> Task<TContinuationResult> continueWithTask(
        @NonNull Continuation<TResult, Task<TContinuationResult>> continuation) {
    try {
        return continuation.then(this);
    } catch (Exception e) {
        return Tasks.forException(unwrap(e));
    }
}
 
Example #19
Source File: SnapshotCoordinator.java    From android-basic-samples with Apache License 2.0 5 votes vote down vote up
public Task<SnapshotsClient.DataOrConflict<Snapshot>> open(final SnapshotsClient snapshotsClient,
                                                           final String filename,
                                                           final boolean createIfNotFound) {

  return setIsOpeningTask(filename).continueWithTask(new Continuation<Void, Task<SnapshotsClient.DataOrConflict<Snapshot>>>() {
    @Override
    public Task<SnapshotsClient.DataOrConflict<Snapshot>> then(@NonNull Task<Void> task) throws Exception {
      return snapshotsClient.open(filename, createIfNotFound)
          .addOnCompleteListener(createOpenListener(filename));
    }
  });
}
 
Example #20
Source File: SnapshotCoordinator.java    From android-basic-samples with Apache License 2.0 5 votes vote down vote up
public Task<SnapshotsClient.DataOrConflict<Snapshot>> open(final SnapshotsClient snapshotsClient,
                                                           final String filename,
                                                           final boolean createIfNotFound,
                                                           final int conflictPolicy) {

  return setIsOpeningTask(filename).continueWithTask(new Continuation<Void, Task<SnapshotsClient.DataOrConflict<Snapshot>>>() {
    @Override
    public Task<SnapshotsClient.DataOrConflict<Snapshot>> then(@NonNull Task<Void> task) throws Exception {
      return snapshotsClient.open(filename, createIfNotFound, conflictPolicy)
          .addOnCompleteListener(createOpenListener(filename));
    }
  });
}
 
Example #21
Source File: TranslateViewModel.java    From quickstart-android with Apache License 2.0 5 votes vote down vote up
public Task<String> translate() {
    final String text = sourceText.getValue();
    final Language source = sourceLang.getValue();
    final Language target = targetLang.getValue();
    if (source == null || target == null || text == null || text.isEmpty()) {
        return Tasks.forResult("");
    }
    int sourceLangCode =
            FirebaseTranslateLanguage.languageForLanguageCode(source.getCode());
    int targetLangCode =
            FirebaseTranslateLanguage.languageForLanguageCode(target.getCode());
    FirebaseTranslatorOptions options = new FirebaseTranslatorOptions.Builder()
            .setSourceLanguage(sourceLangCode)
            .setTargetLanguage(targetLangCode)
            .build();
    final FirebaseTranslator translator =
            FirebaseNaturalLanguage.getInstance().getTranslator(options);
    return translator.downloadModelIfNeeded().continueWithTask(
            new Continuation<Void, Task<String>>() {
        @Override
        public Task<String> then(@NonNull Task<Void> task) {
            if (task.isSuccessful()) {
                return translator.translate(text);
            } else {
                Exception e = task.getException();
                if (e == null) {
                    e = new Exception(getApplication().getString(R.string.unknown_error));
                }
                return Tasks.forException(e);
            }
        }
    });
}
 
Example #22
Source File: SolutionCounters.java    From snippets-android with Apache License 2.0 5 votes vote down vote up
public Task<Integer> getCount(final DocumentReference ref) {
    // Sum the count of each shard in the subcollection
    return ref.collection("shards").get()
            .continueWith(new Continuation<QuerySnapshot, Integer>() {
                @Override
                public Integer then(@NonNull Task<QuerySnapshot> task) throws Exception {
                    int count = 0;
                    for (DocumentSnapshot snap : task.getResult()) {
                        Shard shard = snap.toObject(Shard.class);
                        count += shard.count;
                    }
                    return count;
                }
            });
}
 
Example #23
Source File: MainActivity.java    From drive-android-quickstart with Apache License 2.0 5 votes vote down vote up
/**
 * Creates an {@link IntentSender} to start a dialog activity with configured {@link
 * CreateFileActivityOptions} for user to create a new photo in Drive.
 */
private Task<Void> createFileIntentSender(DriveContents driveContents, Bitmap image) {
  Log.i(TAG, "New contents created.");
  // Get an output stream for the contents.
  OutputStream outputStream = driveContents.getOutputStream();
  // Write the bitmap data from it.
  ByteArrayOutputStream bitmapStream = new ByteArrayOutputStream();
  image.compress(Bitmap.CompressFormat.PNG, 100, bitmapStream);
  try {
    outputStream.write(bitmapStream.toByteArray());
  } catch (IOException e) {
    Log.w(TAG, "Unable to write file contents.", e);
  }

  // Create the initial metadata - MIME type and title.
  // Note that the user will be able to change the title later.
  MetadataChangeSet metadataChangeSet =
      new MetadataChangeSet.Builder()
          .setMimeType("image/jpeg")
          .setTitle("Android Photo.png")
          .build();
  // Set up options to configure and display the create file activity.
  CreateFileActivityOptions createFileActivityOptions =
      new CreateFileActivityOptions.Builder()
          .setInitialMetadata(metadataChangeSet)
          .setInitialDriveContents(driveContents)
          .build();

  return mDriveClient
      .newCreateFileActivityIntentSender(createFileActivityOptions)
      .continueWith(
          new Continuation<IntentSender, Void>() {
            @Override
            public Void then(@NonNull Task<IntentSender> task) throws Exception {
              startIntentSenderForResult(task.getResult(), REQUEST_CODE_CREATOR, null, 0, 0, 0);
              return null;
            }
          });
}
 
Example #24
Source File: StorageTask.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a new Task that will be completed with the result of applying the specified
 * Continuation to this Task.
 *
 * @param executor the executor to use to call the Continuation
 * @see Continuation#then(Task)
 */
@NonNull
@Override
public <ContinuationResultT> Task<ContinuationResultT> continueWithTask(
    @NonNull final Executor executor,
    @NonNull final Continuation<ResultT, Task<ContinuationResultT>> continuation) {
  return continueWithTaskImpl(executor, continuation);
}
 
Example #25
Source File: BaseDemoActivity.java    From android-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Prompts the user to select a folder using OpenFileActivity.
 *
 * @param openOptions Filter that should be applied to the selection
 * @return Task that resolves with the selected item's ID.
 */
private Task<DriveId> pickItem(OpenFileActivityOptions openOptions) {
    mOpenItemTaskSource = new TaskCompletionSource<>();
    getDriveClient()
            .newOpenFileActivityIntentSender(openOptions)
            .continueWith((Continuation<IntentSender, Void>) task -> {
                startIntentSenderForResult(
                        task.getResult(), REQUEST_CODE_OPEN_ITEM, null, 0, 0, 0);
                return null;
            });
    return mOpenItemTaskSource.getTask();
}
 
Example #26
Source File: StorageTask.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a new Task that will be completed with the result of applying the specified
 * Continuation to this Task.
 *
 * @param executor the executor to use to call the Continuation
 * @see Continuation#then(Task)
 */
@NonNull
@Override
public <ContinuationResultT> Task<ContinuationResultT> continueWith(
    @NonNull final Executor executor,
    @NonNull final Continuation<ResultT, ContinuationResultT> continuation) {
  return continueWithImpl(executor, continuation);
}
 
Example #27
Source File: Onboarding.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
public SettingsController retrieveSettingsData(
    Context context, FirebaseApp app, Executor backgroundExecutor) {
  final String googleAppId = app.getOptions().getApplicationId();

  SettingsController controller =
      SettingsController.create(
          context,
          googleAppId,
          idManager,
          requestFactory,
          versionCode,
          versionName,
          getOverridenSpiEndpoint(),
          dataCollectionArbiter);

  // Kick off actually fetching the settings.
  controller
      .loadSettingsData(backgroundExecutor)
      .continueWith(
          backgroundExecutor,
          new Continuation<Void, Object>() {
            @Override
            public Object then(@NonNull Task<Void> task) throws Exception {
              if (!task.isSuccessful()) {
                Logger.getLogger().e("Error fetching settings.", task.getException());
              }
              return null;
            }
          });

  return controller;
}
 
Example #28
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 #29
Source File: Utils.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
/** Similar to Tasks.call, but takes a Callable that returns a Task. */
public static <T> Task<T> callTask(Executor executor, Callable<Task<T>> callable) {
  final TaskCompletionSource<T> tcs = new TaskCompletionSource<T>();
  executor.execute(
      new Runnable() {
        @Override
        public void run() {
          try {
            callable
                .call()
                .continueWith(
                    new Continuation<T, Void>() {
                      @Override
                      public Void then(@NonNull Task<T> task) throws Exception {
                        if (task.isSuccessful()) {
                          tcs.setResult(task.getResult());
                        } else {
                          tcs.setException(task.getException());
                        }
                        return null;
                      }
                    });
          } catch (Exception e) {
            tcs.setException(e);
          }
        }
      });
  return tcs.getTask();
}
 
Example #30
Source File: CrashlyticsBackgroundWorker.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
/** Convenience method that creates a new Continuation that wraps the given callable. */
private <T> Continuation<Void, T> newContinuation(Callable<T> callable) {
  return new Continuation<Void, T>() {
    @Override
    public T then(@NonNull Task<Void> task) throws Exception {
      // We can ignore the task passed in, which is just the queue's tail.
      return callable.call();
    }
  };
}