We recently had a bug reported by a user who was seeing strange behaviors within the “then do” part of a RealtimeDB.Save
block which was within a loop block. The strange part was that even though each execution of the RealtimeDB.Save
block was called with the current value of the loop variable (or something based on the current value) the blocks within the “then do” part always just saw the last value of the loop variable!
This is a well known issue when using asynchronous function blocks (like RealtimeDB.Save
) within a loop. Asynchronous functions are ones which run independently of the other blocks that they are contained within. They exist because you usually do not want functions like RealtimeDB.Save
, which might take a long time to execute, to block the execution of other code. RealtimeDB.Save
can take a long time to execute because it sends and receives data over the web.
In the long run, we need to make it easier to deal with scenarios like this. In the short run, here’s a workaround. The basic idea is to create your own recursive looping function block. Recursive functions are ones that call themselves within their definition. I have created a project which shows a (hopefully) simple example of this, looping over RealtimeDB.Save
. That project can be copied by following this link.
The app has two buttons which when pressed will loop from 1 to 10, storing the loop variable values into a RealtimeDB
and then displaying the loop variable values after each Save
. The first button uses a normal loop and show the behavior that you are complaining about. The second button uses the approach that I am suggesting as a workaround and shows all the loop variable values.
There’s also a third button that you can press to get the value stored at a particular key (which you can enter via a Text Input
) in the RealtimeDB
. That functionality is just provided for convenience and testing.
The key part of the project is seen in these blocks:
You’ll need to adapt those blocks for your own use.
I hope this helps.
Happy Thunking!
-Mark