Last active
February 16, 2022 07:50
-
-
Save Starnamics/bc6380fb9d8695c2c3c47e3ec3313a87 to your computer and use it in GitHub Desktop.
Messenger v0.1.1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--[[ | |
Messenger is a wrapper for Roblox's MessagingService | |
Author: Starnamics | |
License: MIT License | |
Version: 0.1.1 | |
--]] | |
local MessagingService = game:GetService("MessagingService") | |
local EventCache = {} | |
MessagingService:SubscribeAsync("__MESSENGER_TOPIC__", function(MessageData) | |
local Topic: string = MessageData.Data["Topic"] | |
local Message: any = MessageData.Data["Message"] | |
local JobId: string? = MessageData.Data["JobId"] | |
if not Topic or not Message then return end | |
if JobId and game.JobId ~= JobId then return end | |
local Event = EventCache[Topic] | |
if not Event then return end | |
Event:Fire(Message) | |
end) | |
local Messenger = {} | |
function Messenger.new(Topic: string) | |
if Topic and typeof(Topic) == "string" then | |
if not EventCache[Topic] then | |
local Event = Instance.new("BindableEvent") | |
EventCache[Topic] = Event | |
Event.Name = "TOPIC_"..Topic | |
end | |
local TopicObject = {} | |
TopicObject.Topic = Topic | |
function TopicObject:SubscribeAsync(Callback: (any?) -> any?): RBXScriptConnection? | |
if not Callback then warn("SubscribeAsync() requires a callback argument") return end | |
return EventCache[TopicObject.Topic].Event:Connect(Callback) | |
end | |
function TopicObject:PublishAsync(Message: any,JobId: string?) | |
if not Message then warn("PublishAsync() requires a message argument") return end | |
MessagingService:PublishAsync("__MESSENGER_TOPIC__",{["Topic"] = TopicObject.Topic,["Message"] = Message,["JobId"] = JobId}) | |
return | |
end | |
return TopicObject | |
else | |
warn("Messenger.new() requires a topic argument") | |
return | |
end | |
end | |
return Messenger |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment