Coroutine Inside Connection Unwanted Yield

I want to create a coroutine with a connection inside. I want to be able to yield the coroutine without the connected connection currently running halting.

I know I could use Connection:Disconnect() and DeBounce but at the scales I’m working at it would be such a hassle and would be unreadable.

I’ve tried variations of this code but I can’t figure it out. Do I really have to use Connection Disconnects or DeBounce? I know that a created coroutine when yielded doesn’t disturb a wrapped coroutine inside, but when the wrapped coroutine is inside a connection it doesn’t work and stops everything.

Also important, I want to be able to both start and stop this process. Like coroutines resume and yield.

An easy example:

local RunService = game:GetService("RunService")

local RunServiceSteppedListener = coroutine.create(function() --// On Yield
	RunService.Stepped:Connect(function() --// I want to disconnect
		coroutine.wrap(function()
			OnRunServiceStepped() --// But not yield this when running
		end)()
	end)
end)

coroutine.resume(RunServiceSteppedListener)

function OnRunServiceStepped()
	print(1)
	coroutine.yield(RunServiceSteppedListener)
	print(2) --// I want to be able to print 2
end


Continues printing 1 and 2 after yield:

local Coroutine = coroutine.create(function()
	coroutine.wrap(function()
		while task.wait() do
			print(2)
		end
	end)()
	while task.wait() do
		print(1)
	end
end)

coroutine.resume(Coroutine)
task.wait(1)
coroutine.yield(Coroutine)


Oscillates like the last one but after yield only prints 2:

local Coroutine = coroutine.create(function()
	coroutine.wrap(function()
		while task.wait() do
			print(2)
		end
	end)()
	while task.wait() do
		print(1)
	end
end)

coroutine.resume(Coroutine)
task.wait(1)
coroutine.close(Coroutine)

I made a module on my own as I didn’t get any replies. It works quite well.

local Listener = {}
Listener.__index = Listener

function Listener:Create(Signal: RBXScriptSignal, Callback: "function")
	
	local self = setmetatable({}, Listener)
	
	self.Signal = Signal
	self.Callback = Callback
	self.Connection = nil
	
	self.Create = nil
	
	return self
	
end

function Listener:Destroy()
	
	self:Disconnect()
	
	table.clear(self)
	
end

function Listener:Start()
	
	local Signal = self.Signal
	local Callback = self.Callback
	
	local Connection = Signal:Connect(function(...)
		
		--// Trick to bypass non varag function restriction:
		local Arguments = {...} 
		
		coroutine.wrap(function()
			
			Callback(unpack(Arguments))
			
		end)()
		
	end)
	
	self.Connection = Connection
	
end

function Listener:Stop()
	
	local Connection = self.Connection
	
	Connection:Disconnect()
	
end

return Listener

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.