How to detect when datastore changed

So I have this script:

-- Getting services / vars
local ds = game:GetService("DataStoreService")
local coinsdata = ds:GetDataStore("Coins")
local xpdata = ds:GetDataStore("XP")
local leveldata = ds:GetDataStore("Level")

-- Folder creation
game.Players.PlayerAdded:Connect(function(plr) -- Folder added & IntValues
	local folder = Instance.new("Folder")
	folder.Name = "PlayerData"
	folder.Parent = plr
	
	local coinsval = Instance.new("IntValue")
	coinsval.Name = "Coins"
	coinsval.Parent = folder
	coinsval.Value = coinsdata:GetAsync(plr.UserId)
	
	local xpval = Instance.new("IntValue")
	xpval.Name = "XP"
	xpval.Parent = folder
	xpval.Value = xpdata:GetAsync(plr.UserId)
	
	local levelval = Instance.new("IntValue")
	levelval.Name = "Level"
	levelval.Parent = folder
	levelval.Value = leveldata:GetAsync(plr.UserId)
end)

and I am trying to update the int values whenever a datastore value changes. Of course I can’t do a while loop because my requests will be throttled. (Data are stored in a folder inside the player so I can read them from local scripts too.)

1 Like

You’ll have to compare to the whole data every time, but when does the datastore value change without player intervention? Administration power?

Instead, try updating the player’s current data, than the data from the data store, from the update. You can probably try to use MessagingService to send the new update across the servers from a random one. If that player is not online, you can simply update the data from the data store instead, executed by the server which initially fired the MessagingService.

2 Likes

I’m curious too. ds.Changed doesn’t seem to work.

That’s because Changed would fire when a property of the DataStore object changes (GetDataStore returns a DataStore instance which you use to interface with the DataStore endpoints). OnUpdate would be the proper way to do this but it’s deprecated and doesn’t work properly.

You should be writing a method wrapper so that you can fire off a signal every time you commit a DataStore request. For example, instead of only calling SetAsync you’d call a function that both performs SetAsync and PublishAsync for MessagingService to communicate a data change.

Long polling is the only option if you’re trying to do this operation in reverse (assuming Roblox still won’t support web sockets later) but that’ll only be relevant when you can interact with DataStore endpoints with Open Cloud. Right now the only way you can read and write from DataStores is from a Roblox experience server.

2 Likes

You can technically just save the old data to a different key and then compare the new data to that key