मैं कर रहा हूँ परेशानी हो रही पुन: प्राप्त करने Firestore getdocument से पहले डेटा को देखें । मुझे पता है कि यह लौटने के मूल्यों से कई चेक और शायद वहाँ है एक समस्या के साथ मैं कैसे संभाल अतुल्यकालिक कार्य करता है ।
मेरे तीन चर है कि मैं कोशिश कर रहा हूँ करने के लिए सेट.
@Published var numParticipants = 0
@Published var totalAnswered = 0
@Published var showResults = false
यह पहली बार है कि समारोह हो जाता है और सेट प्रतिभागियों की संख्या चर है.
func getRoom(roomId: String, onSuccess: @escaping(_ room: Room) -> Void) {
DB.collection("Rooms").document(roomId).addSnapshotListener { document, error in
DispatchQueue.main.async {
if let dict = document?.data() {
guard let decodeRoom = try? Room.init(fromDictionary: dict) else { return }
onSuccess(decodeRoom)
}
}
}
}
यह दूसरा कार्य है कि हो जाता है और सेट की कुल के जवाब दिए चर
func getNumParticipants(roomId: String, onSuccess: @escaping(_ numParticipants: Int) -> Void) {
DB.collection("RoomsParticipants").document(roomId).collection("Participants").getDocuments { snapshot, error in
DispatchQueue.main.async {
if let error = error {
print(error.localizedDescription)
return
} else {
onSuccess(snapshot!.count)
}
}
}
}
और फिर मैं का उपयोग यह पिछले समारोह की तुलना करने के लिए दो चर और देखें यदि वे बराबर हैं, अन्यथा बस इंतज़ार करो जब तक वे कर रहे हैं के बराबर है ।
func checkShowResults(roomId: String) {
isLoading = true
self.getNumParticipants(roomId: roomId) { numParticipants in
print("Number of docs: \(numParticipants)")
DispatchQueue.main.async {
self.numParticipants = numParticipants
}
}
self.getRoom(roomId: roomId) { room in
print("Total answered: \(room.totalAnswered)")
DispatchQueue.main.async {
self.totalAnswered = room.totalAnswered
if self.totalAnswered == self.numParticipants {
self.showResults = true
}
}
}
isLoading = false
}
यहाँ परिणाम है कि देखने की कोशिश कर रहा हूँ प्रदर्शित करने के लिए बंद आधारित दिलवाया डेटा.
struct ResultsView: View {
@StateObject var resultsViewModel = ResultsViewModel()
var roomId: String
var body: some View {
VStack {
if !resultsViewModel.showResults {
VStack {
ProgressView()
Text("Waiting for all participants \nto finish answering...")
}
} else {
ShowResultsView()
}
}
}
}.navigationBarHidden(true)
.onAppear {
resultsViewModel.checkShowResults(roomId: roomId)
}
}
यहां तक कि अगर totalAnswered और numParticipants के बराबर हैं जब देखने के लिए शुरू में प्रदर्शित, showResults हमेशा के लिए false करने के लिए सेट. लेकिन जब डेटा परिवर्तन यह के अंत में सेट हो जाता है के लिए सच है अगर वे बराबर हो जाते हैं फिर से. मुझे लगता है कि यह है क्योंकि API कॉल करने के लिए firebase/firestore ले जा रहा है समय और चर सेट नहीं कर रहे हैं से पहले देखें । मैं वास्तव में नहीं चाहते हैं, का उपयोग करने के लिए async/इंतजार है ।