Home > Back-end >  Is it safe to do a potential infinite while loop to write data in firebase?
Is it safe to do a potential infinite while loop to write data in firebase?

Time:01-04

I'm using firebase in my app and most of the time it writes the values on the firebase entry with this instruction.

ref.setValue(result);

But on some rare occasions value is not written.

So I have thought about doing this:

boolean finished=false;
[...]  

t=new Thread(new Runnable() {
                        @Override
                        public void run() {
                        while (!finished)
                        {
                            ref.setValue(result, new DatabaseReference.CompletionListener() {
                                @Override
                                public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
                                    finished=true;
                                }
                        }
                            });
                            t.sleep(50);
                        }
                    });
                    t.start();

As most of the time the data is written successfully, it looks like even if an error where to happen when wrting data, it would end up being written successfully anyway.

But maybe this is not enough to ensure that the data ends up being written and it may cause an infinite loop, getting one database error after another.

Is this a good approach to solve the problem?

CodePudding user response:

I would say no this is not a good solution, a better solution would be a counter and a maximum number of retries say 10 this removes the risk of an infinite loop in the case of constant database errors. While still allowing multiple tries to insert the data correctly into the firebase database.

CodePudding user response:

The Realtime Database client already runs all network operations in a background thread. This means that all operations take place without blocking your main thread. Trying to create a new Thread, does not give any benefits at all. Besides that, trying to use:

t.sleep(50);

Might work, if the request takes less than 50 milliseconds. How about 51? That's not how you should deal with asynchronous operations. However, the solution is always the same. Any code that needs to be used when the write operation completes, needs to be inside the onComplete method, or be called from there. If you want to learn how to handle asynchronous operations, I recommend you check my answer from the following post:

If you understand Kotlin, I also recommend you read the following article:

  • Related