diff --git a/samples/snippets/src/main/java/pubsub/SubscribeSyncExample.java b/samples/snippets/src/main/java/pubsub/SubscribeSyncExample.java index 1ece29c37..e3a034044 100644 --- a/samples/snippets/src/main/java/pubsub/SubscribeSyncExample.java +++ b/samples/snippets/src/main/java/pubsub/SubscribeSyncExample.java @@ -60,12 +60,21 @@ public static void subscribeSyncExample( // Use pullCallable().futureCall to asynchronously perform this operation. PullResponse pullResponse = subscriber.pullCallable().call(pullRequest); + + // Stop the program if the pull response is empty to avoid acknowledging + // an empty list of ack IDs. + if (pullResponse.getReceivedMessagesList().isEmpty()) { + System.out.println("No message was pulled. Exiting."); + return; + } + List ackIds = new ArrayList<>(); for (ReceivedMessage message : pullResponse.getReceivedMessagesList()) { // Handle received message // ... ackIds.add(message.getAckId()); } + // Acknowledge received messages. AcknowledgeRequest acknowledgeRequest = AcknowledgeRequest.newBuilder() diff --git a/samples/snippets/src/main/java/pubsub/SubscribeSyncWithLeaseExample.java b/samples/snippets/src/main/java/pubsub/SubscribeSyncWithLeaseExample.java index e074aa3fa..67b604203 100644 --- a/samples/snippets/src/main/java/pubsub/SubscribeSyncWithLeaseExample.java +++ b/samples/snippets/src/main/java/pubsub/SubscribeSyncWithLeaseExample.java @@ -38,9 +38,6 @@ public static void main(String... args) throws Exception { String subscriptionId = "your-subscription-id"; Integer numOfMessages = 10; - projectId = "tz-playground-bigdata"; - subscriptionId = "uno"; - subscribeSyncWithLeaseExample(projectId, subscriptionId, numOfMessages); } @@ -68,8 +65,14 @@ public static void subscribeSyncWithLeaseExample( // Use pullCallable().futureCall to asynchronously perform this operation. PullResponse pullResponse = subscriber.pullCallable().call(pullRequest); - List ackIds = new ArrayList<>(); + // Stop the program if the pull response is empty to avoid acknowledging + // an empty list of ack IDs. + if (pullResponse.getReceivedMessagesList().isEmpty()) { + System.out.println("No message was pulled. Exiting."); + return; + } + List ackIds = new ArrayList<>(); for (ReceivedMessage message : pullResponse.getReceivedMessagesList()) { ackIds.add(message.getAckId());