3 回答

TA貢獻(xiàn)1796條經(jīng)驗(yàn) 獲得超10個(gè)贊
在常規(guī)JVM上,可以使用常規(guī)Java同步原語來實(shí)現(xiàn)。
例如:
// create a java.util.concurrent.Semaphore with 0 initial permits
final Semaphore semaphore = new Semaphore(0);
// attach a value listener to a Firebase reference
ref.addValueEventListener(new ValueEventListener() {
// onDataChange will execute when the current value loaded and whenever it changes
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// TODO: do whatever you need to do with the dataSnapshot
// tell the caller that we're done
semaphore.release();
}
@Override
public void onCancelled(FirebaseError firebaseError) {
}
});
// wait until the onDataChange callback has released the semaphore
semaphore.acquire();
// send our response message
ref.push().setValue("Oh really? Here is what I think of that");
但這在Android上不起作用。這是一件好事,因?yàn)樵谟绊懹脩艚缑娴娜魏问挛镏惺褂眠@種類型的阻止方法都是一個(gè)壞主意。我留下這些代碼的唯一原因是因?yàn)槲倚枰M(jìn)行單元測試。
在實(shí)際的面向用戶的代碼中,您應(yīng)該采用事件驅(qū)動(dòng)的方法。因此,我會(huì)“當(dāng)數(shù)據(jù)進(jìn)入時(shí),發(fā)送我的消息”,而不是“等待數(shù)據(jù)到達(dá)然后發(fā)送我的消息”:
// attach a value listener to a Firebase reference
ref.addValueEventListener(new ValueEventListener() {
// onDataChange will execute when the current value loaded and whenever it changes
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// TODO: do whatever you need to do with the dataSnapshot
// send our response message
ref.push().setValue("Oh really? Here is what I think of that!");
}
@Override
public void onCancelled(FirebaseError firebaseError) {
}
});
最終結(jié)果是完全相同的,但是此代碼不需要同步,并且在Android上不會(huì)阻塞。

TA貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超13個(gè)贊
import com.google.android.gms.tasks.Tasks;
Tasks.await(taskFromFirebase);

TA貢獻(xiàn)1780條經(jīng)驗(yàn) 獲得超5個(gè)贊
我想出了另一種同步獲取數(shù)據(jù)的方式。前提條件是不在UI線程上。
final TaskCompletionSource<List<Objects>> tcs = new TaskCompletionSource<>();
firebaseDatabase.getReference().child("objects").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Mapper<DataSnapshot, List<Object>> mapper = new SnapshotToObjects();
tcs.setResult(mapper.map(dataSnapshot));
}
@Override
public void onCancelled(DatabaseError databaseError) {
tcs.setException(databaseError.toException());
}
});
Task<List<Object>> t = tcs.getTask();
try {
Tasks.await(t);
} catch (ExecutionException | InterruptedException e) {
t = Tasks.forException(e);
}
if(t.isSuccessful()) {
List<Object> result = t.getResult();
}
我測試了我的解決方案,它工作正常,但請(qǐng)證明我錯(cuò)了!
- 3 回答
- 0 關(guān)注
- 773 瀏覽
添加回答
舉報(bào)