How to return something in messaging service?

I want to make it so if a script uses messagingService:PublishAsync("Topic", "Message) to publish something, how would I make it so, when a script is subscribed to the topic it will return something back to the script that published the async?

(Like a bind-able function, or remote function?)

You can always listen on the server who initially sent the request on a second Topic which the other servers can send the data back to.

messagingService:PublishAsync("Topic", {
    JobId = game.JobId,
    Message = "Message"
})

-- Receive responses
messagingService:SubscribeAsync("TopicResponse", function(data)
    if data.JobId == game.JobId then
        -- This response is for our server
    end
end)
1 Like

The second argument of :PublishAsync is the data you’re giving back to the callback bound in :SubscribeAsync.

@SimplyData the topic needs to be the same

1 Like

It makes sense to have a topic for only responses, having a topic to consist of posting and responding could lead to mishaps.

2 Likes

hmm actually not a bad idea now that i think of it. the receiving side gets 1 topic and sending side the other or something like that?

1 Like

mmk @incapaxx, and @ReturnedTrue. So it would look something like so:?:

local msgService = game:GetService("MessagingService")

messagingService:PublishAsync("Topic", "I am messaging you about this. ... ")

local disconnect = false

local success, errorDubug, connection = pcall(function()
    messagingService:SubscribeAsync("ReturnTopic", function(message)
        disconnect = true
    end)
end)

if disconnect then
    connection:Disconnect()
end

messagingService:SubscribeAsync("Topic", function(message)
    if message.Data == "Something" then
        messagingService:PublishAsync("ReturnTopic", "I am returning this. ...")
    end
end)

Or am I not understanding something?

You’re getting the right end of the sticck here, basically you send for it to send back.
Just make sure you include the JobId checks like @SimplyData showed.

FYI: You’d need to return the SubscribeAsync to get the connection which would be the second argument returned anywho.

You might as well disconnect the connection inside itself:

local Connection do
    Connection = MessagingService:SubscribeAsync("Topic", function()
        Connection:Disconnect()
    end)
end
1 Like