PcoWSkbVqDnWTu_dm2ix
Collapse Sidebar

SubscribeAsync

This function registers a callback to begin listening to the given topic. The callback is invoked when a topic receives a message. It can be called multiple times for the same topic.

Callback

The callback is invoked with two arguments:

Field Summary

Data

Developer supplied payload

Sent

Unix time in seconds at which the message was sent

It yields until the subscription is properly registered and returns a connection object.

To unsubscribe, call Datatype/RBXScriptConnection|:Disconnect() on the returned object. Once Disconnect() is called, the callback should never be invoked. Killing the script containing the connections also causes the underlying connect to be unsubscribed.

See also

  • articles/cross server messaging|Cross-Server Messaging Guide, explores how to communicate between game servers in greater detail with relevant code samples
  • MessagingService/PublishAsync, sends the provided message to all subscribers to the topic, triggering their registered callbacks to be invoked

Parameters

Name Type Default Description

Determines where to listen for messages

Function to be invoked whenever a message is received

Returns

Return Type Summary

Connection that can be used to unsubscribe from the topic


Code Samples


Subscribing to Cross Server Messages

This example demonstrates how to use MessengerService/SubscribeAsync to listen to a topic for cross-server chat within a game universe.

When a player joins, the example subscribes to the topic player-<player.UserId>. When a message is sent with this topic, the connected callback executes and prints Received message for <player.Name”>. It also disconnects the connection when the player’s Player/AncestryChanged|ancestry changes.

In order for this to work as expected it must be placed in a server Script.