Pub/Sub

Setup

Here is how to use the Pub/Sub service of the Crewdle SDK. Each user wanting to join the Pub/Sub must open a topic with the same name and the specified type of data it wants to send/receive.

The IChatMessage interface is an example of the type of data that can be sent through the Pub/Sub making it type restricted according to your needs. It can be any type of JSON serializable interface.

import { ContentType } from '@crewdle/web-sdk-types';

interface IChatMessage {
  message: string;
}

const pubSub = cluster.openPubSubTopic<IChatMessage>('pubSub');

You can now either subscribe to the Pub/Sub to allow you to receive messages or files.

pubsub.subscribe(ContentType.Data, (userId: string, content: IChatMessage) => {
  console.log(`${userId} sent a message that reads ${content.message}`)
});

pubsub.subscribe(ContentType.File, (userId: string, content: File) => {
  console.log(`${userId} sent a file with the name ${content.name}`)
});

Or you can publish a message or a file to everyone or specified users.

pubsub.publish({ message: 'Hello Crewdle users' })
pubsub.publish(new File(['Writing', 'a', 'file'], 'crewdleFile'), ['crewdleUser2', 'crewdleUser3'])

When you no longer need to receive messages, you can either unsubscribe from the stream or close it altogether.

pubsub.unsubscribe(ContentType.Data)
pubsub.unsubscribe(ContentType.File)

pubsub.close()

Additional Resources

See the Getting Started section for more information about initiating the SDK and a cluster.

To see a full example of a Pub/Sub being used, checkout our Pub/Sub sample. For more information on the services used in this page, head to our SDK reference