Skip to content

Commit ab828a0

Browse files
samples: exit early if no messages are returned (#989)
* samples: exit early if no messages are pulled * address kurtis's comments * update comment
1 parent 9a1cc0e commit ab828a0

File tree

2 files changed

+16
-4
lines changed

2 files changed

+16
-4
lines changed

samples/snippets/src/main/java/pubsub/SubscribeSyncExample.java

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,12 +60,21 @@ public static void subscribeSyncExample(
6060

6161
// Use pullCallable().futureCall to asynchronously perform this operation.
6262
PullResponse pullResponse = subscriber.pullCallable().call(pullRequest);
63+
64+
// Stop the program if the pull response is empty to avoid acknowledging
65+
// an empty list of ack IDs.
66+
if (pullResponse.getReceivedMessagesList().isEmpty()) {
67+
System.out.println("No message was pulled. Exiting.");
68+
return;
69+
}
70+
6371
List<String> ackIds = new ArrayList<>();
6472
for (ReceivedMessage message : pullResponse.getReceivedMessagesList()) {
6573
// Handle received message
6674
// ...
6775
ackIds.add(message.getAckId());
6876
}
77+
6978
// Acknowledge received messages.
7079
AcknowledgeRequest acknowledgeRequest =
7180
AcknowledgeRequest.newBuilder()

samples/snippets/src/main/java/pubsub/SubscribeSyncWithLeaseExample.java

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -38,9 +38,6 @@ public static void main(String... args) throws Exception {
3838
String subscriptionId = "your-subscription-id";
3939
Integer numOfMessages = 10;
4040

41-
projectId = "tz-playground-bigdata";
42-
subscriptionId = "uno";
43-
4441
subscribeSyncWithLeaseExample(projectId, subscriptionId, numOfMessages);
4542
}
4643

@@ -68,8 +65,14 @@ public static void subscribeSyncWithLeaseExample(
6865
// Use pullCallable().futureCall to asynchronously perform this operation.
6966
PullResponse pullResponse = subscriber.pullCallable().call(pullRequest);
7067

71-
List<String> ackIds = new ArrayList<>();
68+
// Stop the program if the pull response is empty to avoid acknowledging
69+
// an empty list of ack IDs.
70+
if (pullResponse.getReceivedMessagesList().isEmpty()) {
71+
System.out.println("No message was pulled. Exiting.");
72+
return;
73+
}
7274

75+
List<String> ackIds = new ArrayList<>();
7376
for (ReceivedMessage message : pullResponse.getReceivedMessagesList()) {
7477
ackIds.add(message.getAckId());
7578

0 commit comments

Comments
 (0)