【发布时间】:2016-06-30 22:27:16
【问题描述】:
我有两个任务 - task1() 和 task2()。 task1() 从 Internet 获取一个值并将其添加到名为 num 的 int 变量中。 task1() 和 task2() 都可以访问变量 num。 task2() 只是应该打印变量 num 的值。
但这里的问题是,在从 Internet 获取值之前,num 变量被打印出来。
int num = 0;
public static void main(String[] args)
{
task1();
task2();
}
public static void task1()
{
int fetchedValue;
rootRef.addListenerForSingleValueEvent(new ValueEventListener() {
public void onDataChange(DataSnapshot snapshot) {
fetchedValue = Integer.parseInt(snapshot.getValue().toString());
num = num + fetchedValue ;
}
public void onCancelled(FirebaseError arg0) {
System.out.println("cancelled");
}
});
num = num + fetchedValue;
}
public static void task2()
{
System.out.println("Updated number : "+num);
}
【问题讨论】:
-
从 task1() 的 onPostExecute() 调用 task2()。
-
我使用
Firebase不是异步任务。 -
使用EventBus 在第一个任务结束时发布一个事件,并在收到该事件后启动第二个任务。
-
如您所写,
task1是同步的。请在代码中显示>> -
在
onDataChange()方法结束时调用task2。
标签: java firebase firebase-realtime-database