BindToClose & Data Loss Risk

BindToClose() will hold off shutting down the data model until one of the following is true:

  • All BindToClose() callbacks have returned (if they yield, it will wait for them) AND all outstanding data store requests have finished
  • 30 seconds have passed

As far as I know, the best thing to do is to:

  • Start all of your player data saving tasks simultaneously.
  • Only return from the BindToClose callback when all tasks have finished.

Your examples seem to rely on a framework. I’ll provide an example in terms that don’t require unspecified framework behavior.

game:BindToClose(function()
    local tasks = {}
    for _,player in pairs(Players:GetPlayers()) do
        tasks[#tasks+1] = function()
            -- this function shouldn't return until it's finished its task
            -- I assume you do that like this using your framework
            save = DataService:saveData(Player) 
	    save:Fire()
	    save.Event:Wait()
        end
    end

    local numComplete = 0
    local finished = Instance.new("BindableEvent")

    for i = 1, #tasks do
        spawn(function()
            pcall(tasks[i]) -- handle errors somehow
            numComplete = numComplete + 1
            if numComplete == #tasks then
                finished:Fire()
            end
        end)
    end

    finished:Wait()
end)
10 Likes