PcoWSkbVqDnWTu_dm2ix
We use cookies on this site to enhance your user experience
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

  • MessagingService/PublishAsync, invokes the supplied callback whenever a message is pushed to the topic

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.

local messagingService = game:getService("MessagingService")
local players = game:GetService("Players")
 
players.PlayerAdded:connect(function(player)
    --subscribe to the topic
    local topic = "player-" .. player.UserId
    local connection = messagingService:SubscribeAsync(topic, function(message)
        print("Received message for " .. player.Name)
    end)
 
    player.AncestryChanged:connect(function()
        -- unsubscribe from the topic
        connection:Disconnect()
    end)
end)