Name:
interface
Value:
Amplify has re-imagined the way frontend developers build fullstack applications. Develop and deploy without the hassle.

Page updated Apr 29, 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;

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

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:

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

Unsubscribe

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

const sub1 = pubsub.subscribe({ topics: 'myTopicA' }).subscribe({
next: (data) => console.log('Message received', data),
error: (error) => console.error(error),
complete: () => console.log('Done')
});
sub1.unsubscribe();
// 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.

import { CONNECTION_STATE_CHANGE, ConnectionState } from '@aws-amplify/pubsub';
import { Hub } from 'aws-amplify/utils';
Hub.listen('pubsub', (data: any) => {
const { payload } = data;
if (payload.event === CONNECTION_STATE_CHANGE) {
const connectionState = payload.data.connectionState as ConnectionState;
console.log(connectionState);
}
});

Connection issues and automated reconnection

const fetchRecentData = () => {
// Retrieve recent data from some sort of data storage service
}
let priorConnectionState: ConnectionState;
Hub.listen("pubsub", (data: any) => {
const { payload } = data;
if (
payload.event === CONNECTION_STATE_CHANGE
) {
if (priorConnectionState === ConnectionState.Connecting && payload.data.connectionState === ConnectionState.Connected) {
fetchRecentData();
}
priorConnectionState = payload.data.connectionState;
}
});
pubsub.subscribe('myTopic').subscribe({
next: data => // Process incoming messages
})