Tránh memory leak bằng cách: không giữ strong reference đến Activity/View (dùng weak ref), unregister listener khi không dùng, implement singleton đúng cách với application context.
- Lưu ý:
viewModelScopevàlifecycleScopetự động bị cancel khi ViewModel cleared hoặc lifecycle destroyed — chỉ cần cancel thủ công với customCoroutineScope. - Dùng
LeakCanaryđể tự động phát hiện leak. - Monitor bằng memory tab trong Android Profiler.
Avoid memory leaks by: not holding strong references to Activities/Views (use weak refs), unregistering listeners when done, and properly implementing singletons with application context.
- Note:
viewModelScopeandlifecycleScopeare automatically cancelled when the ViewModel is cleared or lifecycle is destroyed — manual cancellation is only needed for customCoroutineScope. - Use
LeakCanaryto detect leaks automatically. - Monitor with Android Profiler's memory tab.