Repository navigation
Stop sharing one listener handle between the stars and comments queries - #1875
rootkiller6788 wants to merge 4 commits into
Conversation
updateStars() watches posts/<id> and fetchComments() watches post-comments/<id>, but both wrote their DatabaseHandle into the same refHandle. Whichever ran last won, so onViewDisappear() and onDetailViewDisappear() were calling removeObserver(withHandle:) on a path that handle was never registered on - one of the two listeners always stayed attached. Give each listener its own handle and clear it after removing.
PostCell calls onViewAppear() from onAppear, which SwiftUI fires again every time the row scrolls back into view. Each call added another observer on posts/<id> without removing the old one, and the closures hold self, so those PostViewModels were never released either.
onViewDisappear() called removeAllObservers() on Database.root, but the observer actually lives on /posts or /user-posts/<uid>, so nothing was ever detached and the refHandle we kept was never read. Remember the reference we observed and remove the handle from that one.
There was a problem hiding this comment.
Code Review
This pull request refactors observer management in PostListViewModel and PostViewModel to prevent stacking duplicate listeners when views reappear, introducing specific handles (postHandle, commentsHandle, and observedRef) and cleanup logic. The review feedback highlights critical memory leak risks due to strong reference cycles in the observer closures of fetchComments(), updateStars(), and fetchPosts(). To address this, self should be captured weakly in these closures, and deinit methods should be implemented to ensure proper cleanup when the view models are deallocated.
The observer closures captured self strongly, so Firebase kept each PostViewModel and PostListViewModel alive for as long as its listener was registered, and deinit could never run to clean it up. Capture self weakly and remove whatever listener is still attached in deinit.
paulb777
left a comment
There was a problem hiding this comment.
Thanks for tracking this down, and for the clear write-up! I checked the listener bookkeeping against the SDK, and the fixes hold up:
- Shared handle in
PostViewModel:removeObserver(withHandle:)matches on both the location and the handle, and handles are unique across locations, so handing the comments handle toposts/<id>(or the other way around) was a silent no-op. On macOS, where the list stays visible next to the detail, every detail visit leaked a stars listener. PostListViewModel.onViewDisappear():removeAllObservers()only clears listeners registered at that exact location. Calling it on the root never detached/postsoruser-posts/<uid>, so every tab switch or return from a detail view stacked another listener.[weak self]+deinit: this covers the gemini-code-assist comments, so those threads can be resolved.
I left a few optional nits inline. Two more things:
- Could you retitle the PR, e.g. "Fix Realtime Database listener leaks in the SwiftUI sample"? It now carries three fixes, and the title becomes the squash commit subject.
- A couple of claims in the description and commit messages are stronger than what the old code did. Could you adjust them so the squash message stays accurate?
- Scrolling alone didn't stack stars listeners.
PostCell.onDisappearalready removed the listener, as long as the comments handle hadn't overwrittenrefHandle. It took a detail-view visit (or an unbalancedonAppear) to orphan one. PostCellkeeps its model in a@StateObject, so a row that's already on screen keeps the firstPostViewModelit was created with. The instances rebuilt for it on each/postsevent never register listeners, so whole batches weren't being stranded. What leaked was one orphaned listener (and its view model) per detail visit, plus the/postslisteners piling up inPostListViewModel.
- Scrolling alone didn't stack stars listeners.
| deinit { | ||
| // The observer closures only hold `self` weakly, so deinit can run while a | ||
| // listener is still registered. Hand each handle back to the reference it | ||
| // was registered on so nothing outlives the view model. | ||
| if let postHandle = postHandle { | ||
| ref.child("posts").child(id).removeObserver(withHandle: postHandle) | ||
| } | ||
| if let commentsHandle = commentsHandle { | ||
| ref.child("post-comments").child(id).removeObserver(withHandle: commentsHandle) | ||
| } | ||
| } |
There was a problem hiding this comment.
Optional: each listener's remove-by-path code now lives in three places: here, at the top of updateStars() / fetchComments(), and in onViewDisappear() / onDetailViewDisappear(). One helper per listener, like PostListViewModel.removeObserver(), keeps each path in one spot and makes the remove-before-observe pattern easy to follow in the sample. With the suggestion below, updateStars() / fetchComments() can start with removeStarsObserver() / removeCommentsObserver(), and the two *Disappear() methods can just call them.
| deinit { | |
| // The observer closures only hold `self` weakly, so deinit can run while a | |
| // listener is still registered. Hand each handle back to the reference it | |
| // was registered on so nothing outlives the view model. | |
| if let postHandle = postHandle { | |
| ref.child("posts").child(id).removeObserver(withHandle: postHandle) | |
| } | |
| if let commentsHandle = commentsHandle { | |
| ref.child("post-comments").child(id).removeObserver(withHandle: commentsHandle) | |
| } | |
| } | |
| deinit { | |
| // The observer closures only hold `self` weakly, so deinit can run while a | |
| // listener is still registered. Detach both so nothing outlives the view model. | |
| removeStarsObserver() | |
| removeCommentsObserver() | |
| } | |
| private func removeStarsObserver() { | |
| if let postHandle = postHandle { | |
| ref.child("posts").child(id).removeObserver(withHandle: postHandle) | |
| self.postHandle = nil | |
| } | |
| } | |
| private func removeCommentsObserver() { | |
| if let commentsHandle = commentsHandle { | |
| ref.child("post-comments").child(id).removeObserver(withHandle: commentsHandle) | |
| self.commentsHandle = nil | |
| } | |
| } |
| @@ -182,14 +207,16 @@ class PostViewModel: ObservableObject, Identifiable { | |||
|
|
|||
| // remove all handlers when current view disappears | |||
There was a problem hiding this comment.
Nit: this now only removes the stars listener; onDetailViewDisappear() handles the comments one.
| // remove all handlers when current view disappears | |
| // remove the stars listener when the post row disappears |
| deinit { | ||
| // The observer closure holds `self` weakly, so make sure a listener that | ||
| // outlived the view is detached when the view model goes away. | ||
| removeObserver() | ||
| } |
There was a problem hiding this comment.
Nit (optional): consider moving deinit up next to the stored properties so it comes before the methods, the way PostViewModel has it right after its initializers.
| private func removeObserver() { | ||
| if let refHandle = refHandle, let observedRef = observedRef { | ||
| observedRef.removeObserver(withHandle: refHandle) | ||
| } | ||
| refHandle = nil | ||
| observedRef = nil | ||
| } |
There was a problem hiding this comment.
Nice catch. removeAllObservers() only clears listeners registered at that exact location, so the root call never detached the /posts or user-posts/<uid> listener. Keeping the observed reference around is the right fix.
The Realtime Database SwiftUI sample never actually detaches its listeners.
PostViewModelhas a singlerefHandle, but two listeners write to it:updateStars()watchesposts/<id>,fetchComments()watchespost-comments/<id>. Whichever runs last wins the field, so one of the tworemoveObserver(withHandle:)calls inonViewDisappear()/onDetailViewDisappear()is always given a handle that was never registered on that path. Following the normal flow: the row appears and the stars listener registers, tapping into the detail registers the comments listener and clobbers it, coming back outonViewDisappear()tries to drop the stars listener with the comments handle and does nothing. The stars listener stays onposts/<id>forever.That leaks more than a listener. Both observer closures capture
self, andPostListViewModel.fetchPostsbuilds a whole new batch ofPostViewModels on every/postsvalue event, so each write strands the previous batch. Same thing without ever opening the detail view:onAppearfires again every time a row scrolls back into view andupdateStars()just stacks another observer on the same path.So I gave each listener its own handle, and made
updateStars()/fetchComments()drop their previous listener before registering a new one.Last commit is the same bug one level up.
PostListViewModel.onViewDisappear()callsremoveAllObservers()onDatabase.root, but the observer lives on/postsor/user-posts/<uid>, andremoveAllObservers()only touches the node you call it on. Nothing was detached there either, and therefHandleit stored was never read. It now remembers the reference it observed and removes the handle from that one.I don't have Xcode on this machine, so this is from reading the listener bookkeeping rather than from a run - flag anything that doesn't line up and I'll dig in.