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!

1回答
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
エキスパート
回答済み 6ヶ月前
profile pictureAWS
エキスパート
Greg_B
レビュー済み 6ヶ月前

ログインしていません。 ログイン 回答を投稿する。

優れた回答とは、質問に明確に答え、建設的なフィードバックを提供し、質問者の専門分野におけるスキルの向上を促すものです。

質問に答えるためのガイドライン

関連するコンテンツ