File tree Expand file tree Collapse file tree 2 files changed +32
-14
lines changed
firestore/FirestoreSwiftUIExample Expand file tree Collapse file tree 2 files changed +32
-14
lines changed Original file line number Diff line number Diff line change @@ -10,22 +10,37 @@ class RestaurantListViewModel: ObservableObject {
10
10
11
11
@Published var restaurants = [ Restaurant] ( )
12
12
private var db = Firestore . firestore ( )
13
+ private var listener : ListenerRegistration ?
13
14
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
+ }
20
33
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
+ }
27
42
}
28
- } ?? [ ]
43
+ }
29
44
}
30
45
}
31
46
Original file line number Diff line number Diff line change @@ -18,7 +18,10 @@ struct ContentView: View {
18
18
}
19
19
. navigationBarTitle ( " Friendly Eats " , displayMode: . inline)
20
20
. onAppear ( ) {
21
- self . restaurantListViewModel. fetchData ( )
21
+ restaurantListViewModel. subscribe ( )
22
+ }
23
+ . onDisappear ( ) {
24
+ restaurantListViewModel. unsubscribe ( )
22
25
}
23
26
. toolbar {
24
27
ToolbarItem ( placement: . navigationBarLeading) {
You can’t perform that action at this time.
0 commit comments