Amplify PubSub can't publish unless there is a subscription

0

Hello, I'm using Amplify Pub/Sub in my React Native app (android for now) and it seems I can only publish mqtt message after subscribing to a topic. Without subscription in my app, my publish is never reaching AWS IoT Core. Is this intended or am I missing something?

Thanks!

asked 5 months ago231 views
1 Answer
0

The Amplify PubSub module creates the MQTT WSS connection only when subscribe is invoked, this is why you do not see any publishes if you do not subscribe first. If your application only needs to publish data but not subscribe, you can just call subscribe with an empty array of topics to trigger the connection. Otherwise the publish topics are not correlated to the subscribe topics, ie you can subscribe to topic response and publish to topic answer. Just ensure that you have called subscribe once before calling publish.

See example snippet below.

import { useEffect, useState } from 'react';
import reactLogo from './assets/react.svg';
import viteLogo from '/vite.svg';
import { PubSub } from '@aws-amplify/pubsub';
import '@aws-amplify/ui-react/styles.css';
import './App.css';
import { withAuthenticator } from '@aws-amplify/ui-react';
import { fetchAuthSession } from 'aws-amplify/auth';

const pubsub = new PubSub({
  endpoint: 'wss://abcdxxxxxxx-ats.iot.eu-west-1.amazonaws.com/mqtt',
  region: 'eu-west-1',
});

function App() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    console.log('Publishing ', count);
    pubsub
      .publish({
        topics: 'hello',
        message: { msg: `Hello ${count}` },
      })
      .catch((err) => console.error(err));
  }, [count]);

  useEffect(() => {
    fetchAuthSession().then((info) => {
      console.log(info.identityId);
    });
    // This triggers the connection to the AWS IoT MQTT broker
    pubsub.subscribe({ topics: [] }).subscribe({});

  }, []);

  return (
    <>
      <div>
      <h1>Vite + React</h1>
      <div className="card">
        <button
          onClick={async () => {
            setCount((count) => count + 1);
          }}
        >
          count is {count}
        </button>
        <p>
          Edit <code>src/App.tsx</code> and save to test HMR
        </p>
      </div>
    </>
  );
}

export default withAuthenticator(App);
AWS
EXPERT
answered 5 months ago
profile pictureAWS
EXPERT
Greg_B
reviewed 5 months ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions