問題是關于此代碼(在 Android 應用程式中):
private Task<QuerySnapshot> getVotesFromDB() {
res = new int[]{0, 0, 0}; // a private class-member
return FirebaseFirestore.getInstance().collection("Votes")
.whereEqualTo("proposition_key", curr_proposition.getKey())
.get().addOnCompleteListener(task -> {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
String userChoice = (String) document.get("user_choice");
int choice;
switch (userChoice) {
case "against":
choice = 0;
break;
case "impossible":
choice = 1;
break;
case "agreement":
choice = 2;
break;
default:
throw new IllegalStateException("Unexpected value: " userChoice);
}
res[choice] ;
}
}
});
}
通常,代碼從 Firestore 集合中讀取一些行,并對它們應用一些“業務邏輯”(計算每種型別的字串數)。將來,業務邏輯可能會變得比計數復雜得多。所以我正在尋找一種重構代碼的方法,這樣業務邏輯就可以與資料庫分開撰寫和測驗。我想要的是具有以下形式的功能:
int[] countVotes(Generator<String> strings) {
res = new int[3];
(for String userChoice: strings) {
// Update res as above
}
return res;
}
無需任何資料庫連接即可進行單元測驗。那么,上面的函式可以重構如下:
private Generator<String> getVotesFromDB() {
return FirebaseFirestore.getInstance().collection("Votes")
.whereEqualTo("proposition_key", curr_proposition.getKey())
.get().addOnCompleteListener(task -> {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
userChoice = (String) document.get("user_choice");
yield userChoice;
}
}
});
}
并運行類似的東西:
countVotes(getVotesFromDB())
問題是,我不知道如何使用異步函式呼叫來做到這一點。有沒有辦法以類似或更好的方式重構代碼?
uj5u.com熱心網友回復:
您可以將結果收集到一個陣列中,然后使用單獨的方法對其進行處理。然后,如果處理方法很復雜,則可以針對各種不同的結果串列單獨進行單元測驗。
private void getVotesFromDB() {
FirebaseFirestore.getInstance().collection("Votes")
.whereEqualTo("proposition_key", curr_proposition.getKey())
.get().addOnCompleteListener(task -> {
if (task.isSuccessful()) {
ArrayList<String> results = new ArrayList();
for (QueryDocumentSnapshot document : task.getResult()) {
String userChoice = (String) document.get("user_choice");
results.add(userChoice);
}
// assign the result to a class member
res = countVotes(results);
// do something to signal to the rest of the code
// that results have been processed (e.g. post to
// LiveData or call another "showResults" method)
}
});
}
然后,任何復雜的計數邏輯都可以與 firebase 呼叫分開。
int[] countVotes(ArrayList<String> choices) {
int[] res = new int[]{0,0,0};
// count the votes
return res;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/401133.html
標籤:爪哇 安卓 火力基地 异步 谷歌云firestore
下一篇:如何鍵入以陣列陣列作為輸入的函式
