Page updated Jan 16, 2024

Subscribe and unsubscribe

Subscribe

Subscribe to a topic

In order to start receiving messages from your provider, you need to subscribe to a topic as follows;

1pubsub.subscribe({ topics: 'myTopic' }).subscribe({
2 next: (data) => console.log('Message received', data),
3 error: (error) => console.error(error),
4 complete: () => console.log('Done')
5});

Following events will be triggered with subscribe()

EventDescription
nextTriggered every time a message is successfully received for the topic
errorTriggered when subscription attempt fails
completeTriggered when you unsubscribe from the topic

Subscribe to multiple topics

To subscribe for multiple topics, just pass a String array including the topic names:

1pubsub.subscribe({ topics: ['myTopic1', 'myTopic1'] }).subscribe({
2 //...
3});

Unsubscribe

To stop receiving messages from a topic, you can use unsubscribe() method:

1const sub1 = pubsub.subscribe({ topics: 'myTopicA' }).subscribe({
2 next: (data) => console.log('Message received', data),
3 error: (error) => console.error(error),
4 complete: () => console.log('Done')
5});
6
7sub1.unsubscribe();
8// You will no longer get messages for 'myTopicA'

Subscription connection status updates

Now that your application is setup and using pubsub subscriptions, you may want to know when the subscription is finally established, or reflect to your users when the subscription isn't healthy. You can monitor the connection state for changes via Hub.

1import { CONNECTION_STATE_CHANGE, ConnectionState } from '@aws-amplify/pubsub';
2import { Hub } from 'aws-amplify/utils';
3
4Hub.listen('pubsub', (data: any) => {
5 const { payload } = data;
6 if (payload.event === CONNECTION_STATE_CHANGE) {
7 const connectionState = payload.data.connectionState as ConnectionState;
8 console.log(connectionState);
9 }
10});

Connection issues and automated reconnection

1const fetchRecentData = () => {
2 // Retrieve recent data from some sort of data storage service
3}
4
5let priorConnectionState: ConnectionState;
6
7Hub.listen("pubsub", (data: any) => {
8 const { payload } = data;
9 if (
10 payload.event === CONNECTION_STATE_CHANGE
11 ) {
12
13 if (priorConnectionState === ConnectionState.Connecting && payload.data.connectionState === ConnectionState.Connected) {
14 fetchRecentData();
15 }
16 priorConnectionState = payload.data.connectionState;
17 }
18});
19
20pubsub.subscribe('myTopic').subscribe({
21 next: data => // Process incoming messages
22})