Skip to content

fix(ChatViewModel): add deinit cleanup for NotificationCenter observers and timers #120

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

samyakjain-1
Copy link

@samyakjain-1 samyakjain-1 commented Jul 9, 2025

fix(ChatViewModel): add deinit cleanup for NotificationCenter observers and timers


Summary

Added a deinit method to ChatViewModel to clean up NotificationCenter observers, timers, and Combine subscriptions when the view model is deallocated. Without this, resources would persist beyond the lifecycle of the instance, leading to memory leaks and unpredictable behavior.


Problem

ChatViewModel registers for system notifications during initialization using:

NotificationCenter.default.addObserver(self, selector: ..., name: ..., object: nil)

It also creates:

  • A debounce timer (nicknameSaveTimer) in the nickname setter
  • A Combine subscription (deliveryTrackerCancellable) to track delivery status

Previously, there was no deinit method, so none of these were cleaned up when the object was released. This could lead to:

  • Retained memory (due to observers)
  • Dangling callbacks on deallocated instances
  • Flaky behavior during testing or navigation

Fix

Added a deinit method to the class (within the primary ChatViewModel declaration):

deinit {
    NotificationCenter.default.removeObserver(self)
    nicknameSaveTimer?.invalidate()
    deliveryTrackerCancellable?.cancel()
}

This ensures proper cleanup when the view model is deallocated.


This:

  • Prevents memory leaks: by removing retained observers
  • Improves test reliability: by preventing callbacks on dead objects
  • Brings lifecycle hygiene: in line with best practices used across the codebase

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.

1 participant