Is this a good way of disconnecting an event from the inside

Every once and a while Ill have an event that sometimes I only want it to disconnect depending on the arguments of that event. This is how I’ve been dealing with it so far

local RemoteEvent = Instance.new("RemoteEvent")

function ExampleFunction()
	
	local BoolValue = Instance.new("BoolValue")
	
	local ExampleEvent = RemoteEvent.OnServerEvent:Connect(function(Arguement)
		if Arguement == true then 
			-- Run Code
		else
			BoolValue.Value = true 
		end
	end)
	
	BoolValue.Changed:Wait()
	
	ExampleEvent:Disconnect()
	BoolValue:Destroy()

end

I’m worried now because I’ve started looking more into garbage dumps and memory leaks and I’m worried that creating instances just for a :Wait() is bad practice.

Im not sure if anything is left behind because I know some instances even destroyed are still there (e.g. Bindable Events).

Is this fine to keep using or will this effect my game in the long term.
(Also I know I can just use metamethods for events but I don’t like setting up metatables just for small things like this)

1 Like
local ExampleEvent
ExampleEvent = RemoteEvent.OnServerEvent:Connect(function(Arguement)
	if Arguement == true then
		-- stuff
	else
		ExampleEvent:Disconnect()
	end
end)
2 Likes

No it’s not the best way. Define the variable before making the connection:

local RemoteEvent = Instance.new("RemoteEvent")

function ExampleFunction()
    local ExampleEvent --> predefined variable
    ExampleEvent = RemoteEvent.OnServerEvent:Connect(function(Arguement) --> define the event
        if Arguement == true then 
            -- Run Code
        else
            ExampleEvent:Disconnect() --> you can now disconnect it here
        end
    end)
end

This code above will define the variable first, which lets you access the variable inside the connection after you define it.

1 Like

The above options are excellent, but you can also leverage the :Wait() method:

if RemoteEvent.OnServerEvent:Wait() == true then
	-- Run Code
end
-- do nothing, do not listen to the event again

EDIT: I realized that your original code will not disconnect if the remote’s argument is true.
In this code block, the if has been replaced with a while.

while RemoteEvent.OnServerEvent:Wait() == true do
	-- Run Code
end
-- stop listening

How did I never know you could disconnect an event inside an event.

I was always told that because of the way roblox proccesses threads that it was impossible :man_facepalming:

Thanks for the help