BindToClose() Question

Hello, On This Topic the author suggests BindToClose() like this :

local function onShutdown()
	local finished = Instance.new("BindableEvent")
	local allPlayers = Players:GetPlayers()
	local leftPlayers = #allPlayers

	for _,player in ipairs(allPlayers) do
		coroutine.wrap(function()
			save(player, nil, true)
			leftPlayers -= 1
			if leftPlayers == 0 then
				finished:Fire()
			end
		end)()
	end
	finished.Event:Wait()
end

But i wonder why this BindableEvent is here ? Why not just doing like this :

local function onShutdown()
	local allPlayers = Players:GetPlayers()
	for _,plr in allPlayers do
		coroutine.wrap(function()
			save(plr, true)
		end)
	end
	task.wait()	
end

If someone have an answer it would be great. Thank you

1 Like

so the server waits for all the data to be saved before it dies i guess?

1 Like

Since it is a coroutine.wrap, the function is triggered without any yield , so it shouldn’t wait i guess no ? Maybe it’s for some security about potential inconsistent of the server when shutdown

1 Like

BindToClose allows its callbacks to yield up to ~20 seconds, and after the callback finishes or the limit times out the game immediately closes.

What they are trying to do is wrap the save function in a coroutine, so it doesn’t hang up the loop in case it yields, and then using a BindableEvent to keep the main function yielding.

This is a pretty outdated way of achieving this, though. You should strive to keep yielding logic outside of event handlers like this, and in the case you have to (DataStore Async saving and etc.), you should just spawn each thread and yield for them to finish with the task library. There’s a good library for this in RbxUtil.

1 Like

Thank you for theses informations !

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