Skip to content

Commit 4ed6502

Browse files
committed
properly handle listener
1 parent f44bc4a commit 4ed6502

File tree

2 files changed

+32
-14
lines changed

2 files changed

+32
-14
lines changed

firestore/FirestoreSwiftUIExample/ViewModels/RestaurantListViewModel.swift

Lines changed: 28 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -10,22 +10,37 @@ class RestaurantListViewModel: ObservableObject {
1010

1111
@Published var restaurants = [Restaurant]()
1212
private var db = Firestore.firestore()
13+
private var listener: ListenerRegistration?
1314

14-
func fetchData() {
15-
db.collection("restaurants").addSnapshotListener { (querySnapshot, error) in
16-
if let error = error {
17-
print("Error getting restaurants: \(error.localizedDescription)")
18-
return
19-
}
15+
deinit {
16+
unsubscribe()
17+
}
18+
19+
func unsubscribe() {
20+
if listener != nil {
21+
listener?.remove()
22+
listener = nil
23+
}
24+
}
25+
26+
func subscribe() {
27+
if listener == nil {
28+
listener = db.collection("restaurants").addSnapshotListener { [weak self] (querySnapshot, error) in
29+
guard let documents = querySnapshot?.documents else {
30+
print("Error fetching documents: \(error!)")
31+
return
32+
}
2033

21-
self.restaurants = querySnapshot?.documents.compactMap { document in
22-
do {
23-
return try document.data(as: Restaurant.self)
24-
} catch let error {
25-
print(error)
26-
return nil
34+
guard let self = self else { return }
35+
self.restaurants = documents.compactMap { document in
36+
do {
37+
return try document.data(as: Restaurant.self)
38+
} catch let error {
39+
print(error)
40+
return nil
41+
}
2742
}
28-
} ?? []
43+
}
2944
}
3045
}
3146

firestore/FirestoreSwiftUIExample/Views/ContentView.swift

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,10 @@ struct ContentView: View {
1818
}
1919
.navigationBarTitle("Friendly Eats", displayMode: .inline)
2020
.onAppear() {
21-
self.restaurantListViewModel.fetchData()
21+
restaurantListViewModel.subscribe()
22+
}
23+
.onDisappear() {
24+
restaurantListViewModel.unsubscribe()
2225
}
2326
.toolbar {
2427
ToolbarItem(placement: .navigationBarLeading) {

0 commit comments

Comments
 (0)