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

The following examples show how to use com.google.android.gms.tasks.TaskCompletionSource. 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: Utilities.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
public static Pair<Task<Void>, DatabaseReference.CompletionListener> wrapOnComplete(
    DatabaseReference.CompletionListener optListener) {
  if (optListener == null) {
    final TaskCompletionSource<Void> source = new TaskCompletionSource<>();
    DatabaseReference.CompletionListener listener =
        new DatabaseReference.CompletionListener() {
          @Override
          public void onComplete(DatabaseError error, DatabaseReference ref) {
            if (error != null) {
              source.setException(error.toException());
            } else {
              source.setResult(null);
            }
          }
        };
    return new Pair<>(source.getTask(), listener);
  } else {
    // If a listener is supplied we do not want to create a Task
    return new Pair<>(null, optListener);
  }
}
 
Example #4
Source File: DataTransportCrashlyticsReportSender.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@NonNull
public Task<CrashlyticsReportWithSessionId> sendReport(
    @NonNull CrashlyticsReportWithSessionId reportWithSessionId) {
  final CrashlyticsReport report = reportWithSessionId.getReport();

  TaskCompletionSource<CrashlyticsReportWithSessionId> tcs = new TaskCompletionSource<>();
  transport.schedule(
      Event.ofUrgent(report),
      error -> {
        if (error != null) {
          tcs.trySetException(error);
          return;
        }
        tcs.trySetResult(reportWithSessionId);
      });
  return tcs.getTask();
}
 
Example #5
Source File: DataCollectionArbiter.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@SuppressLint({"CommitPrefEdits", "ApplySharedPref"})
public void setCrashlyticsDataCollectionEnabled(boolean enabled) {
  crashlyticsDataCollectionEnabled = enabled;
  crashlyticsDataCollectionExplicitlySet = true;
  sharedPreferences.edit().putBoolean(FIREBASE_CRASHLYTICS_COLLECTION_ENABLED, enabled).commit();

  synchronized (taskLock) {
    if (enabled) {
      if (!taskResolved) {
        dataCollectionEnabledTask.trySetResult(null);
        taskResolved = true;
      }
    } else {
      if (taskResolved) {
        dataCollectionEnabledTask = new TaskCompletionSource<>();
        taskResolved = false;
      }
    }
  }
}
 
Example #6
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 #7
Source File: GetDownloadUrlTask.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
GetDownloadUrlTask(
    @NonNull StorageReference storageRef, @NonNull TaskCompletionSource<Uri> pendingResult) {
  Preconditions.checkNotNull(storageRef);
  Preconditions.checkNotNull(pendingResult);

  this.storageRef = storageRef;
  this.pendingResult = pendingResult;
  if (storageRef.getRoot().getName().equals(storageRef.getName())) {
    throw new IllegalArgumentException(
        "getDownloadUrl() is not supported at the root of the bucket.");
  }
  FirebaseStorage storage = this.storageRef.getStorage();
  sender =
      new ExponentialBackoffSender(
          storage.getApp().getApplicationContext(),
          storage.getAuthProvider(),
          storage.getMaxOperationRetryTimeMillis());
}
 
Example #8
Source File: ListTask.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
ListTask(
    @NonNull StorageReference storageRef,
    @Nullable Integer maxResults,
    @Nullable String pageToken,
    @NonNull TaskCompletionSource<ListResult> pendingResult) {
  Preconditions.checkNotNull(storageRef);
  Preconditions.checkNotNull(pendingResult);

  this.storageRef = storageRef;
  this.maxResults = maxResults;
  this.pageToken = pageToken;
  this.pendingResult = pendingResult;

  FirebaseStorage storage = this.storageRef.getStorage();
  sender =
      new ExponentialBackoffSender(
          storage.getApp().getApplicationContext(),
          storage.getAuthProvider(),
          storage.getMaxDownloadRetryTimeMillis());
}
 
Example #9
Source File: GetMetadataTask.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
GetMetadataTask(
    @NonNull StorageReference storageRef,
    @NonNull TaskCompletionSource<StorageMetadata> pendingResult) {
  Preconditions.checkNotNull(storageRef);
  Preconditions.checkNotNull(pendingResult);

  this.mStorageRef = storageRef;
  this.mPendingResult = pendingResult;
  if (storageRef.getRoot().getName().equals(storageRef.getName())) {
    throw new IllegalArgumentException(
        "getMetadata() is not supported at the root of the bucket.");
  }

  FirebaseStorage storage = mStorageRef.getStorage();
  mSender =
      new ExponentialBackoffSender(
          storage.getApp().getApplicationContext(),
          storage.getAuthProvider(),
          storage.getMaxDownloadRetryTimeMillis());
}
 
Example #10
Source File: DisplayCallbacksImpl.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Converts an rx maybe to task.
 *
 * <p>Since the semantics of maybe are different from task, we adopt the following rules.
 *
 * <ul>
 *   <li>Maybe that resolves to a value is resolved to a succeeding task
 *   <li>Maybe that resolves to an exception is resolved to a failed task
 *   <li>Maybe that resolves to an error is resolved to a failed task with a wrapped exception
 *   <li>Maybe that resolves to empty is resolved to succeeding Void Task
 * </ul>
 */
private static <T> Task<T> maybeToTask(Maybe<T> maybe, Scheduler scheduler) {
  TaskCompletionSource<T> tcs = new TaskCompletionSource<>();
  Disposable ignoredDisposable =
      maybe
          .doOnSuccess(tcs::setResult)
          .switchIfEmpty(
              Maybe.fromCallable(
                  () -> {
                    tcs.setResult(null);
                    return null;
                  }))
          .onErrorResumeNext(
              throwable -> {
                if (throwable instanceof Exception) {
                  tcs.setException((Exception) throwable);
                } else {
                  tcs.setException(new RuntimeException(throwable));
                }
                return Maybe.empty();
              })
          .subscribeOn(scheduler)
          .subscribe();

  return tcs.getTask();
}
 
Example #11
Source File: DisplayCallbacksImpl.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@Override
public Task<Void> displayErrorEncountered(InAppMessagingErrorReason errorReason) {
  /**
   * NOTE: While the api is passing us the campaign id via the FIAM, we pull the campaignId from
   * the cache to ensure that we're only logging events for campaigns that we've fetched - to
   * avoid implicitly trusting an id that is provided through the app
   */
  String RENDER_ERROR = "render error to metrics logger";
  if (shouldLog()) {
    Logging.logd("Attempting to record: " + RENDER_ERROR);

    Completable completable =
        Completable.fromAction(
            () -> metricsLoggerClient.logRenderError(inAppMessage, errorReason));

    return maybeToTask(
        logToImpressionStore().andThen(completable).andThen(updateWasImpressed()).toMaybe(),
        schedulers.io());
  }
  logActionNotTaken(RENDER_ERROR);
  return new TaskCompletionSource<Void>().getTask();
}
 
Example #12
Source File: AsyncQueue.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Initiate the shutdown process. Once called, the only possible way to run `Runnable`s are by
 * holding the `internalExecutor` reference.
 */
private synchronized Task<Void> executeAndInitiateShutdown(Runnable task) {
  if (isShuttingDown()) {
    TaskCompletionSource<Void> source = new TaskCompletionSource<>();
    source.setResult(null);
    return source.getTask();
  }

  // Not shutting down yet, execute and return a Task.
  Task<Void> t =
      executeAndReportResult(
          () -> {
            task.run();
            return null;
          });

  // Mark the initiation of shut down.
  isShuttingDown = true;

  return t;
}
 
Example #13
Source File: TestCommandHelper.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
public static Task<StringBuilder> testDownloadUrl(StorageReference ref) {
  TaskCompletionSource<StringBuilder> result = new TaskCompletionSource<>();
  StringBuilder builder = new StringBuilder();
  builder.append("Getting Download Url.\n");
  Task<Uri> getDownloadUrl = ref.getDownloadUrl();

  getDownloadUrl.addOnCompleteListener(
      executor,
      task -> {
        builder.append("Received Download Url.\n");
        builder.append("getDownloadUrl:").append(task.getResult());
        builder.append("\nonComplete:Success=\n").append(task.isSuccessful());
        result.setResult(builder);
      });
  return result.getTask();
}
 
Example #14
Source File: SpecTestCase.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
private void doMutation(Mutation mutation) throws Exception {
  DocumentKey documentKey = mutation.getKey();
  TaskCompletionSource<Void> callback = new TaskCompletionSource<>();
  Task<Void> writeProcessed =
      callback
          .getTask()
          .continueWith(
              backgroundExecutor,
              task -> {
                if (task.isSuccessful()) {
                  SpecTestCase.this.acknowledgedDocs.add(documentKey);
                } else {
                  SpecTestCase.this.rejectedDocs.add(documentKey);
                }
                return null;
              });

  getCurrentOutstandingWrites().add(new Pair<>(mutation, writeProcessed));
  log("      Sending this write: " + mutation);
  queue.runSync(() -> syncEngine.writeMutations(singletonList(mutation), callback));
}
 
Example #15
Source File: SyncEngine.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
/** Resolves the task corresponding to this write result. */
private void notifyUser(int batchId, @Nullable Status status) {
  Map<Integer, TaskCompletionSource<Void>> userTasks = mutationUserCallbacks.get(currentUser);

  // NOTE: Mutations restored from persistence won't have task completion sources, so it's okay
  // for this (or the task below) to be null.
  if (userTasks != null) {
    Integer boxedBatchId = batchId;
    TaskCompletionSource<Void> userTask = userTasks.get(boxedBatchId);
    if (userTask != null) {
      if (status != null) {
        userTask.setException(Util.exceptionFromStatus(status));
      } else {
        userTask.setResult(null);
      }
      userTasks.remove(boxedBatchId);
    }
  }
}
 
Example #16
Source File: SyncEngine.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Takes a snapshot of current mutation queue, and register a user task which will resolve when
 * all those mutations are either accepted or rejected by the server.
 */
public void registerPendingWritesTask(TaskCompletionSource<Void> userTask) {
  if (!remoteStore.canUseNetwork()) {
    Logger.debug(
        TAG,
        "The network is disabled. The task returned by 'awaitPendingWrites()' will not "
            + "complete until the network is enabled.");
  }

  int largestPendingBatchId = localStore.getHighestUnacknowledgedBatchId();

  if (largestPendingBatchId == MutationBatch.UNKNOWN) {
    // Complete the task right away if there is no pending writes at the moment.
    userTask.setResult(null);
    return;
  }

  if (!pendingWritesCallbacks.containsKey(largestPendingBatchId)) {
    pendingWritesCallbacks.put(largestPendingBatchId, new ArrayList());
  }

  pendingWritesCallbacks.get(largestPendingBatchId).add(userTask);
}
 
Example #17
Source File: DisplayCallbacksImpl.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@Override
public Task<Void> impressionDetected() {

  // In the future, when more logAction events are supported, it might be worth
  // extracting this logic into a manager similar to InAppMessageStreamManager
  String MESSAGE_IMPRESSION = "message impression to metrics logger";

  if (shouldLog() && !wasImpressed) {
    Logging.logd("Attempting to record: " + MESSAGE_IMPRESSION);

    Completable logImpressionToMetricsLogger =
        Completable.fromAction(() -> metricsLoggerClient.logImpression(inAppMessage));

    Completable logImpressionCompletable =
        logToImpressionStore()
            .andThen(logImpressionToMetricsLogger)
            .andThen(updateWasImpressed());

    return maybeToTask(logImpressionCompletable.toMaybe(), schedulers.io());
  }
  logActionNotTaken(MESSAGE_IMPRESSION);
  return new TaskCompletionSource<Void>().getTask();
}
 
Example #18
Source File: FirebaseFirestore.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Clears the persistent storage, including pending writes and cached documents.
 *
 * <p>Must be called while the {@code FirebaseFirestore} instance is not started (after the app is
 * shutdown or when the app is first initialized). On startup, this method must be called before
 * other methods (other than {@link #setFirestoreSettings(FirebaseFirestoreSettings)}). If the
 * {@code FirebaseFirestore} instance is still running, the {@code Task} will fail with an error
 * code of {@code FAILED_PRECONDITION}.
 *
 * <p>Note: {@code clearPersistence()} is primarily intended to help write reliable tests that use
 * Cloud Firestore. It uses an efficient mechanism for dropping existing data but does not attempt
 * to securely overwrite or otherwise make cached data unrecoverable. For applications that are
 * sensitive to the disclosure of cached data in between user sessions, we strongly recommend not
 * enabling persistence at all.
 *
 * @return A {@code Task} that is resolved when the persistent storage is cleared. Otherwise, the
 *     {@code Task} is rejected with an error.
 */
@NonNull
public Task<Void> clearPersistence() {
  final TaskCompletionSource<Void> source = new TaskCompletionSource<>();
  asyncQueue.enqueueAndForgetEvenAfterShutdown(
      () -> {
        try {
          if (client != null && !client.isTerminated()) {
            throw new FirebaseFirestoreException(
                "Persistence cannot be cleared while the firestore instance is running.",
                Code.FAILED_PRECONDITION);
          }
          SQLitePersistence.clearPersistence(context, databaseId, persistenceKey);
          source.setResult(null);
        } catch (FirebaseFirestoreException e) {
          source.setException(e);
        }
      });
  return source.getTask();
}
 
Example #19
Source File: DisplayCallbacksImpl.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@Override
public Task<Void> messageDismissed(InAppMessagingDismissType dismissType) {

  /**
   * NOTE: While the api is passing us the campaign id via the FIAM, we pull the campaignId from
   * the cache to ensure that we're only logging events for campaigns that we've fetched - to
   * avoid implicitly trusting an id that is provided through the app
   */
  String MESSAGE_DISMISSAL = "message dismissal to metrics logger";
  if (shouldLog()) {
    Logging.logd("Attempting to record: " + MESSAGE_DISMISSAL);
    Completable completable =
        Completable.fromAction(() -> metricsLoggerClient.logDismiss(inAppMessage, dismissType));

    return logImpressionIfNeeded(completable);
  }
  logActionNotTaken(MESSAGE_DISMISSAL);
  return new TaskCompletionSource<Void>().getTask();
}
 
Example #20
Source File: DisplayCallbacksImpl.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@Override
public Task<Void> messageClicked(Action action) {

  /**
   * NOTE: While the api is passing us the campaign id via the FIAM, we pul the campaignId from
   * the cache to ensure that we're only logging events for campaigns that we've fetched - to
   * avoid implicitly trusting an id that is provided through the app
   */
  if (shouldLog()) {
    if (action.getActionUrl() == null) {
      return messageDismissed(InAppMessagingDismissType.CLICK);
    }
    return logMessageClick(action);
  }
  logActionNotTaken(MESSAGE_CLICK);
  return new TaskCompletionSource<Void>().getTask();
}
 
Example #21
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 #22
Source File: SyncEngine.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
private void addUserCallback(int batchId, TaskCompletionSource<Void> userTask) {
  Map<Integer, TaskCompletionSource<Void>> userTasks = mutationUserCallbacks.get(currentUser);
  if (userTasks == null) {
    userTasks = new HashMap<>();
    mutationUserCallbacks.put(currentUser, userTasks);
  }
  userTasks.put(batchId, userTask);
}
 
Example #23
Source File: SyncEngine.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Initiates the write of local mutation batch which involves adding the writes to the mutation
 * queue, notifying the remote store about new mutations, and raising events for any changes this
 * write caused. The provided task will be resolved once the write has been acked/rejected by the
 * backend (or failed locally for any other reason).
 */
public void writeMutations(List<Mutation> mutations, TaskCompletionSource<Void> userTask) {
  assertCallback("writeMutations");

  LocalWriteResult result = localStore.writeLocally(mutations);
  addUserCallback(result.getBatchId(), userTask);

  emitNewSnapsAndNotifyLocalStore(result.getChanges(), /*remoteEvent=*/ null);
  remoteStore.fillWritePipeline();
}
 
Example #24
Source File: FirestoreClient.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a task resolves when all the pending writes at the time when this method is called
 * received server acknowledgement. An acknowledgement can be either acceptance or rejections.
 */
public Task<Void> waitForPendingWrites() {
  this.verifyNotTerminated();

  final TaskCompletionSource<Void> source = new TaskCompletionSource<>();
  asyncQueue.enqueueAndForget(() -> syncEngine.registerPendingWritesTask(source));
  return source.getTask();
}
 
Example #25
Source File: FirestoreClient.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
/** Writes mutations. The returned task will be notified when it's written to the backend. */
public Task<Void> write(final List<Mutation> mutations) {
  this.verifyNotTerminated();
  final TaskCompletionSource<Void> source = new TaskCompletionSource<>();
  asyncQueue.enqueueAndForget(() -> syncEngine.writeMutations(mutations, source));
  return source.getTask();
}
 
Example #26
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 #27
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 #28
Source File: SnapshotCoordinator.java    From android-basic-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a task that will complete when given file is closed.  Returns immediately if the
 * file is not open.
 *
 * @param filename - the file name in question.
 */
public Task<Result> waitForClosed(String filename) {
  final TaskCompletionSource<Result> taskCompletionSource = new TaskCompletionSource<>();

  final CountDownLatch latch;
  synchronized (this) {
    latch = opened.get(filename);
  }

  if (latch == null) {
    taskCompletionSource.setResult(null);

    return taskCompletionSource.getTask();
  }

  new AsyncTask<Void, Void, Void>() {
    @Override
    protected Void doInBackground(Void... voids) {
      Result result = new CountDownTask(latch).await();
      taskCompletionSource.setResult(result);

      return null;
    }
  }.execute();

  return taskCompletionSource.getTask();
}
 
Example #29
Source File: SyncEngine.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
/** Resolves tasks waiting for this batch id to get acknowledged by server, if there are any. */
private void resolvePendingWriteTasks(int batchId) {
  if (pendingWritesCallbacks.containsKey(batchId)) {
    for (TaskCompletionSource<Void> task : pendingWritesCallbacks.get(batchId)) {
      task.setResult(null);
    }

    pendingWritesCallbacks.remove(batchId);
  }
}
 
Example #30
Source File: DefaultSettingsControllerTest.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
public void testCachedSettingsLoad_newInstanceIdentifier() throws Exception {
  final SettingsData fetchedSettings = new TestSettingsData();

  final JSONObject fetchedJson = new JSONObject();
  when(mockSettingsSpiCall.invoke(any(SettingsRequest.class), eq(true))).thenReturn(fetchedJson);

  when(mockSettingsJsonParser.parseSettingsJson(fetchedJson)).thenReturn(fetchedSettings);

  TaskCompletionSource<Void> dataCollectionPermission = new TaskCompletionSource<>();
  when(mockDataCollectionArbiter.waitForDataCollectionPermission())
      .thenReturn(dataCollectionPermission.getTask());

  final SettingsRequest requestData = buildSettingsRequest();
  final SettingsController controller =
      newSettingsController(
          requestData,
          mockCurrentTimeProvider,
          mockSettingsJsonParser,
          mockCachedSettingsIo,
          mockSettingsSpiCall,
          mockDataCollectionArbiter,
          true);

  controller.loadSettingsData(SettingsCacheBehavior.SKIP_CACHE_LOOKUP, networkExecutor);
  assertNotNull(controller.getSettings());

  dataCollectionPermission.trySetResult(null);
  assertEquals(fetchedSettings.appData, await(controller.getAppSettings()));
  assertEquals(fetchedSettings, controller.getSettings());

  verify(mockSettingsSpiCall).invoke(any(SettingsRequest.class), eq(true));
  verify(mockCachedSettingsIo).writeCachedSettings(fetchedSettings.expiresAtMillis, fetchedJson);
  verify(mockSettingsJsonParser).parseSettingsJson(fetchedJson);
  verify(mockCurrentTimeProvider).getCurrentTimeMillis();
}