'Creating an Array of ListenerRegistration in SwiftUI Firestore
I have a list of groups stored in self.groups
I'm looping over these groups, like so
for group in groups {
}
And then I'm attaching a snapshot listener to each group (which is obviously causing the listeners to leak), like so:
for group in groups {
    self.groupListener = ref.addSnapshotListener {...}
}
Then, when my user wants to log out, I call Model.removeAllListeners(), and this works for all listeners set properly, and not inside for-in loops.
However, I've tried to create a @Published var which holds an array of ListenerRegistrations, like so:
@Published var spacesTasksInDayListener: [ListenerRegistration] = []
However, when I do, I get the error:
'ListenerRegistration' is not convertible to '[ListenerRegistration]'
So my question is, how can I keep a reference to each snapshot listener, if its generated inside a for-in loop?
My current solution is to modify my Firestore Snapshot to return all the documents I want using a proper query function, only assigning one snapshot listener, allowing me to remove it at the end.
However, am I incapable of creating an array of listeners?
Thank you!
P.S. I'm trying to reference all my listeners so that I can call listenerRef.remove() when a user logs out
Solution 1:[1]
Okay, so I've found a solution, however I've also changed a lot of my architecture.
The reason I wanted to add snapshotListeners to an array was so that I can build a way around the 10 limit for arrayContains queries, and know when I need to refresh a listener with more things to listen to!
I've created a struct:
enum MySnapshotListenerType: String {
    case groups = "groups"
    case members = "members"
}
struct MySnapshotListener: Identifiable {
    let id: String = UUID().uuidString
    
    var listener: ListenerRegistration?
    var type: MySnapshotListenerType?
    var groupID: String?
    var memberID: String?
}
And whenever I start a new snapshot listener, I create a reference to it, `.remove any existing, matching snapshot listener type, and append the new one.
let newSnapshotReference = path.collection(a_group_id).addSnapshotListener {...}
for snapshotListener in self.snapshotListeners {
    if snapshotListener.type == .groups && snapshotListener.groupID == a_group_id {
        if snapshotListener.listener != nil {
            snapshotListener.listener!.remove()
        }
    }
}
self.snapshotListeners.append(
    MySnapshotListener(
        listener: newSnapshotReference,
        type: .groups,
        groupID: a_group_id
    )
)
And now I can safely remove every snapshot listener on user's logout.
If anyone has any suggestions to make this better I'm all ears :)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source | 
|---|---|
| Solution 1 | Heron. F | 
