Does closing a coroutine disconnect any connections within the corutine?

Not much to put here

Just same as the title, if i have a connection (For example a .touched connection) within a coroutine and then i close the coroutine, does it automatically disconnect the connection or should i disconnect them before closing the coroutine?

you need to manually disconnect the connections

1 Like

local thread = task.defer(function()
	workspace.Part.Touched:Connect(function(otherPart: BasePart)
		local character = otherPart.Parent
		
		local humanoid = character:FindFirstChildOfClass("Humanoid")
		if not humanoid then
			return
		end
		
		print(character.Name .. " touched the part!")
	end)
end)

task.delay(5, function()
	task.cancel(thread)
	
	print("Cancelled thread!")
end)

Tested with the above code. This also shows that despite the RBXScriptConnection being garbage-collected as the thread is killed, the event listener is still connected. This is true for any event listener’s RBXScriptConnection being GC’ed

TL;DR: No. You need to store the RBXScriptConnection returned by RBXScriptSIgnal:Connect and invoke its “Disconnect” method.

1 Like

Suppose the script creating the deffered thread gets deleted; will that destroy the connections?

Original reply

No, because the rbxscriptconnection becomes a property of the event handler of the instance it is connected to.
The script only holds a reference to it, so you must either call the disconnect method on the scripts reference, or destroy the instance (but if you have a script reference this must also be disconnected and set to nil, even when destroying the instance).

I’ve just tested the behaviour of scripts when they are destroyed and getting some really counter intuitive results… but in short, actually yes, destroying the script seems to destroy any connections made within the script, even if they are stored in a module script and are still visible to other scripts.

I’m going based off of this information