Skip to content

Stop sharing one listener handle between the stars and comments queries - #1875

Open
rootkiller6788 wants to merge 4 commits into
firebase:mainfrom
rootkiller6788:fix-rtdb-swiftui-listener-leak
Open

rootkiller6788 wants to merge 4 commits into
firebase:mainfrom
rootkiller6788:fix-rtdb-swiftui-listener-leak

Conversation

@rootkiller6788

Copy link
Copy Markdown

The Realtime Database SwiftUI sample never actually detaches its listeners.

PostViewModel has a single refHandle, but two listeners write to it: updateStars() watches posts/<id>, fetchComments() watches post-comments/<id>. Whichever runs last wins the field, so one of the two removeObserver(withHandle:) calls in onViewDisappear() / 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 out onViewDisappear() tries to drop the stars listener with the comments handle and does nothing. The stars listener stays on posts/<id> forever.

That leaks more than a listener. Both observer closures capture self, and PostListViewModel.fetchPosts builds a whole new batch of PostViewModels on every /posts value event, so each write strands the previous batch. Same thing without ever opening the detail view: onAppear fires again every time a row scrolls back into view and updateStars() 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() calls removeAllObservers() on Database.root, but the observer lives on /posts or /user-posts/<uid>, and removeAllObservers() only touches the node you call it on. Nothing was detached there either, and the refHandle it 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.

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.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@rootkiller6788
rootkiller6788 marked this pull request as ready for review October 16, 2026 03:52
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 paulb777 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 to posts/<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 /posts or user-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:

  1. 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.
  2. 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.onDisappear already removed the listener, as long as the comments handle hadn't overwritten refHandle. It took a detail-view visit (or an unbalanced onAppear) to orphan one.
    • PostCell keeps its model in a @StateObject, so a row that's already on screen keeps the first PostViewModel it was created with. The instances rebuilt for it on each /posts event 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 /posts listeners piling up in PostListViewModel.

Comment on lines +72 to +82
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)
}
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Suggested change
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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: this now only removes the stars listener; onDetailViewDisappear() handles the comments one.

Suggested change
// remove all handlers when current view disappears
// remove the stars listener when the post row disappears

Comment on lines +104 to +108
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()
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +114 to 120
private func removeObserver() {
if let refHandle = refHandle, let observedRef = observedRef {
observedRef.removeObserver(withHandle: refHandle)
}
refHandle = nil
observedRef = nil
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants