Long-running operations (LROs)

Several calls to the API return long-running operations. These track the status of a job which executes over an extended period of time, such that having a blocking RPC is not desirable.

OperationFuture class

The most obvious way to interact with LROs is with the OperationFuture class. If you use this, make sure that the service client is not destroyed.

Not recommended:

private void doSomething() {
  OperationFuture<Empty, Empty> future = startLongRunningOperation(jobName);
  future.get();
}

private OperationFuture<Empty, Empty> startLongRunningOperation(String jobToStart)
    throws UnsupportedEncodingException {
  try (OfflineUserDataJobServiceClient offlineUserDataJobServiceClient =
      googleAdsClient.getLatestVersion().createOfflineUserDataJobServiceClient()) {
    // Issues an asynchronous request to run the offline user data job for executing
    // all added operations.
    return offlineUserDataJobServiceClient.runOfflineUserDataJobAsync(jobToStart);
  }
}

Recommended:

private void doSomethingElse() {
  try (OfflineUserDataJobServiceClient offlineUserDataJobServiceClient =
      googleAdsClient.getLatestVersion().createOfflineUserDataJobServiceClient()) {
    OperationFuture<Empty, Empty> future = startLongRunningOperation(offlineUserDataJobServiceClient, jobName);
    future.get();
  }
}

private OperationFuture<Empty, Empty> startLongRunningOperation(String jobToStart)
    throws UnsupportedEncodingException {
    offlineUserDataJobServiceClient.runOfflineUserDataJobAsync(jobToStart);
}

Notice how the OperationFuture class is only used while the OfflineUserDataJobServiceClient is in scope.