在Java中为异步调用添加超时
-
21-12-2019 - |
题
不仅仅是一个Firebase问题,但我正在使用Firebase从Android向后端发布帖子,并每秒运行一次10次。
Firebase ref = new Firebase(URL);
ref.child("Time").setValue(Currentime());
然而,这是一个异步调用,当我把一个while循环:
while (time_now < time_start + 10 seconds) {
Firebase ref = new Firebase(URL);
ref.child("Time").setValue(Currentime());
}
它似乎首先运行while循环,然后在最后运行~10个Firebase调用。有没有办法添加超时,以便在调用下一个异步调用之前强制异步(Firebase)调用运行一秒钟?
解决方案
如果你看 Firebase网站上的Java示例, ,你会看到它有一个 doTransactions
方法和一个 onComplete
方法:
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);
所以你把新的时间定在 doTransaction
方法:
// set the new time
currentData.setValue(time_now);
return Transaction.success(currentData);
然后在 onComplete
方法。
// transaction committed, do next iteration
if (time_now < time_start + 10 seconds) {
countRef.runTransaction(handler);
}
不隶属于 StackOverflow