maicon santos
maicon santos

Reputation: 141

Fetching and showing if the API JSON response has changed

I am consuming a game API that updates all active player statistics in real time in the game.

I'm trying to make a way for my code to listen to this API (outside of a loop) and when there are changes in your json response, my code will print on the console. I'm currently trying with Ruby ​​Events, but I didn't get anything other than out of a loop (while true).

old_data = ""

while true
    sleep 1
    data = Utils.req("GET", "https://127.0.0.1:2999/liveclientdata/playerscores?summonerName=Yoruku", {}, false) 
    #{"assists":0,"creepScore":50,"deaths":0,"kills":5,"wardScore":0}
    
    next if data.eql? old_data
    old_data = data
    p "NEW DATA: #{data}"
end 


Upvotes: 0

Views: 110

Answers (1)

Kamil Gwóźdź
Kamil Gwóźdź

Reputation: 774

Your code seems to be doing exactly what you want it to do.

You used a technique called polling. It has its issues, like performance and rate limits which you need to consider. But you can't really not use a loop in this case. Because that what polling essentially is.

You could maybe use some async scheduler (like sidekiq) and after each http request you could schedule another one in the future. Or you could use something like sidekiq-cron gem. In that way you can avoid using a loop.

If you want to avoid making requests even when nothing changed on the server you'll need to use some websockets or so called long polling. But idk if the api you to talk to supports it.

Alternatively the api could create a webhook and the api would call you when there is a change.

Upvotes: 2

Related Questions