Adding Timeout to Asynchronous Calls in Java
-
21-12-2019 - |
Question
Not solely a Firebase question, but I am using Firebase to make posts to a backend from Android and run it 10 times, once every second.
Firebase ref = new Firebase(URL);
ref.child("Time").setValue(Currentime());
However this is an Asynchronous Call and when I put a while loop:
while (time_now < time_start + 10 seconds) {
Firebase ref = new Firebase(URL);
ref.child("Time").setValue(Currentime());
}
It seems to run the while loop first and then ~10 Firebase calls at the end. Is there a way to add a timeout so that it forces the Asynchronous (Firebase) calls to run for a second before calling the next Async call?
Solution
If you look at the Java example on the Firebase web site, you'll see that it has a doTransactions
method and an onComplete
method:
Firebase countRef = new Firebase(URL);
Transaction.Handler handler = new Transaction.Handler() {
@Override
public Transaction.Result doTransaction(MutableData currentData) {
// set the new time
...
}
@Override
public void onComplete(FirebaseError error, boolean committed, DataSnapshot currentData) {
if (error != null) {
...
} else {
if (!committed) {
...
} else {
// transaction committed, do next iteration
...
}
...
}
}
});
countRef.runTransaction(handler);
So you'd set the new time in the doTransaction
method:
// set the new time
currentData.setValue(time_now);
return Transaction.success(currentData);
And then start a next iteration in the onComplete
method.
// transaction committed, do next iteration
if (time_now < time_start + 10 seconds) {
countRef.runTransaction(handler);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow