Bird
0
0

Given the following code snippet, what will be printed if the subscription receives a message?

medium📝 service behavior Q13 of 15
GCP - Cloud Pub/Sub
Given the following code snippet, what will be printed if the subscription receives a message?
from google.cloud import pubsub_v1

subscriber = pubsub_v1.SubscriberClient()
subscription_path = subscriber.subscription_path('my-project', 'my-sub')

def callback(message):
    print(f'Received: {message.data.decode()}')
    message.ack()

streaming_pull_future = subscriber.subscribe(subscription_path, callback=callback)
print('Listening for messages...')
AOnly Listening for messages...
BOnly Received: <message content>
CListening for messages... followed by Received: <message content>
DError because callback is not called
Step-by-Step Solution
Solution:
  1. Step 1: Understand code flow

    The code subscribes to a topic and sets a callback to print received messages and acknowledge them.
  2. Step 2: Identify output behavior

    It prints 'Listening for messages...' immediately, then prints 'Received: ...' when a message arrives.
  3. Final Answer:

    Listening for messages... followed by Received: <message content> -> Option C
  4. Quick Check:

    Subscribe prints listening then message received [OK]
Quick Trick: Callback prints message after initial listening print [OK]
Common Mistakes:
  • Assuming callback runs before print
  • Thinking no output until message arrives
  • Ignoring message acknowledgment

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More GCP Quizzes