Skip to content

Commit 00644c6

Browse files
authored
Update subscriber example in README to current patterns. (#6194)
Closes #6189.
1 parent b514515 commit 00644c6

1 file changed

Lines changed: 17 additions & 12 deletions

File tree

README.rst

Lines changed: 17 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -90,9 +90,9 @@ messages to it
9090
.. code-block:: python
9191
9292
import os
93-
from google.cloud import pubsub
93+
from google.cloud import pubsub_v1
9494
95-
publisher = pubsub.PublisherClient()
95+
publisher = pubsub_v1.PublisherClient()
9696
topic_name = 'projects/{project_id}/topics/{topic}'.format(
9797
project_id=os.getenv('GOOGLE_CLOUD_PROJECT'),
9898
topic='MY_TOPIC_NAME', # Set this to something appropriate.
@@ -109,14 +109,14 @@ Subscribing
109109
^^^^^^^^^^^
110110

111111
To subscribe to data in Cloud Pub/Sub, you create a subscription based on
112-
the topic, and subscribe to that.
112+
the topic, and subscribe to that, passing a callback function.
113113

114114
.. code-block:: python
115115
116116
import os
117-
from google.cloud import pubsub
117+
from google.cloud import pubsub_v1
118118
119-
subscriber = pubsub.SubscriberClient()
119+
subscriber = pubsub_v1.SubscriberClient()
120120
topic_name = 'projects/{project_id}/topics/{topic}'.format(
121121
project_id=os.getenv('GOOGLE_CLOUD_PROJECT'),
122122
topic='MY_TOPIC_NAME', # Set this to something appropriate.
@@ -127,17 +127,22 @@ the topic, and subscribe to that.
127127
)
128128
subscriber.create_subscription(
129129
name=subscription_name, topic=topic_name)
130-
subscription = subscriber.subscribe(subscription_name)
131-
132-
The subscription is opened asychronously, and messages are processed by
133-
use of a callback.
134-
135-
.. code-block:: python
136130
137131
def callback(message):
138132
print(message.data)
139133
message.ack()
140-
subscription.open(callback)
134+
135+
future = subscriber.subscribe(subscription_name, callback)
136+
137+
The future returned by the call to ``subscriber.subscribe`` can be used to
138+
block the current thread until a given condition obtains:
139+
140+
.. code-block:: python
141+
142+
try:
143+
future.result()
144+
except KeyboardInterrupt:
145+
future.cancel()
141146
142147
To learn more, consult the `subscriber documentation`_.
143148

0 commit comments

Comments
 (0)