skip to content

How do you make LeakCanary 2 watch an object it does not track automatically, such as a presenter released when its screen closes?

level: seniorimportance: nice to knowfreq 18%

answer

  1. the same object watcher
  2. call it when the object should die
  3. a description shows in the trace
  4. watch() was renamed

basics

~10 s

Call AppWatcher.objectWatcher.expectWeaklyReachable(obj, description) at the moment the object should become garbage. It then follows the same 5-second retention check and heap-dump threshold as activities, and the description appears in the leak trace.

solid answer

~40 s

`AppWatcher.objectWatcher` is the same `ObjectWatcher` the built-in watchers use, so I call `AppWatcher.objectWatcher.expectWeaklyReachable(presenter, "ArticlePresenter received onDestroy()")` right where the presenter is released. From then on it is treated like a destroyed activity: retained if still reachable after 5 seconds and a GC, counted towards the dump threshold, and shown in the trace as "ObjectWatcher was watching this because ..." with my description. Two pitfalls: since 2.6 `watch()` is deprecated in favour of `expectWeaklyReachable()`, and the call must not sit in the `main` source set if LeakCanary is only a `debugImplementation`, or release won't compile. Either put it in debug-only code, or depend on `leakcanary-object-watcher-android` in all builds: it watches and counts retained objects but never dumps the heap.

code

kotlin · 11 lines
kotlin
// src/debug/kotlin/com/example/news/DebugPresenterHooks.kt
import leakcanary.AppWatcher

object DebugPresenterHooks : PresenterHooks {
    override fun onPresenterDestroyed(presenter: Any) {
        AppWatcher.objectWatcher.expectWeaklyReachable(
            watchedObject = presenter,
            description = "${presenter::class.java.simpleName} received onDestroy()"
        )
    }
}

go deeper

for a junior

Know that you can hand any object to AppWatcher.objectWatcher when it should be gone, and LeakCanary then treats it like a destroyed activity.

for a middle

Explain that custom objects follow the same weak reference, 5-second check and dump threshold, and that the description ends up in the trace.

for a senior

Get the timing right, use expectWeaklyReachable rather than the deprecated watch(), and solve the release-compile problem with debug-only code or the object-watcher artifact.

for a principal

Decide which of the team's own lifecycle objects deserve watching and whether release builds should report retained counts, weighing signal against noise and maintenance.

## The built-in watchers are only a default LeakCanary's default watchers cover activities, fragments, fragment views, `ViewModel`s, services and detached root views. Many apps have other objects with a lifecycle of their own: a presenter in an MVP screen, a per-screen dependency-injection component, a detached custom view, a closed resource. LeakCanary cannot know when those should die, so you tell it. ## The call `AppWatcher.objectWatcher` is the `ObjectWatcher` every default watcher feeds. Hand it your object at the moment the object should become unreachable: ```kotlin AppWatcher.objectWatcher.expectWeaklyReachable( watchedObject = this, description = "ArticlePresenter received onDestroy()" ) ``` What happens next is exactly what happens to a destroyed activity: 1. A `KeyedWeakReference` with a random key and your description wraps the object. 2. After `retainedDelayMillis` (5 seconds by default) the watcher checks whether the reference was cleared. 3. If not, the object is **retained**; LeakCanary forces a GC, recounts and adds it to the retained count. 4. When the count reaches the threshold (5 while the app is visible, 1 once in the background), it dumps and analyzes the heap. 5. The trace's last object carries `Leaking: YES (ObjectWatcher was watching this because ArticlePresenter received onDestroy())`. A precise description pays off in the trace: it says why the object was expected to be gone. ## Timing the call Call it **after** the last legitimate reference is released, not before: - Too early (for instance before the presenter detaches from its view or cancels its work) and the object is still legitimately referenced, which produces a false retained object or even a misleading trace. - Never on an object that is meant to live on, such as a cached or pooled instance; LeakCanary will correctly report it as retained, because it is. - An object watched once does not need to be watched again; each call creates a new weak reference. ## API history: watch() vs expectWeaklyReachable() | Call | Status in 2.14 | |---|---| | `expectWeaklyReachable(watchedObject, description)` | current, from the `ReachabilityWatcher` interface added in 2.6 | | `watch(watchedObject, description)` | deprecated in 2.6, renamed to make the intent clear | | `watch(watchedObject)` | deprecated; asks you to add a description | | `RefWatcher` from LeakCanary 1.x | removed in 2.0 | Much of the project's own documentation still shows `watch()`; it compiles with a deprecation warning and behaves the same. ## The release-build trap LeakCanary is normally a `debugImplementation` dependency. A call to `AppWatcher` written in the `main` source set therefore compiles in debug and **fails to compile in release**. There are two clean answers: - **Keep the call in debug-only code**, for example a debug `Application` subclass or a hook that only the debug source set implements. - **Depend on `leakcanary-object-watcher-android` with `implementation`.** This small artifact holds `AppWatcher` and the watchers, keeps weak references to destroyed objects and to whatever you pass it, but never dumps the heap. In release it is cheap, and `AppWatcher.objectWatcher.retainedObjectCount` can be read to attach a retained-object count to crash reports, such as out-of-memory errors. ## Changing the default set instead Watching more is one direction; the same API also lets you narrow the defaults: - Disable the automatic install with the `leak_canary_watcher_auto_install` boolean resource. - Call `AppWatcher.manualInstall(application, watchersToInstall = ...)` with `AppWatcher.appDefaultWatchers(application, reachabilityWatcher)`, where your `ReachabilityWatcher` filters out specific instances and forwards the rest to `AppWatcher.objectWatcher.expectWeaklyReachable()`. - The older `AppWatcher.config` flags such as `watchActivities` are deprecated in favour of this. ## A worked case A news app's article screen uses a presenter that subscribes to a session singleton and is released when the screen closes. Activities are watched already, but the presenter is not, so a presenter that stays subscribed after its screen closes goes unnoticed as long as it no longer points back at the activity. Adding the watch call where the presenter is released changes that: 1. The screen closes; the presenter's release hook calls `expectWeaklyReachable()`. 2. Five seconds later the presenter is still reachable through the singleton's subscriber list, so it is retained. 3. After a few more articles, or as soon as the app goes to the background, LeakCanary dumps the heap. 4. The trace ends at the presenter with your description, and the suspects point at the subscriber list, the registration nobody removed. ## Making the traces of your objects clearer A custom `ObjectInspector`, added through `LeakCanary.config.objectInspectors`, can mark your own types as leaking or not leaking from their state (say, a `destroyed` flag) and add labels such as an id. That narrows the suspect references in traces that pass through your classes, just as the built-in inspectors do for activities and views.

  • What changes if you watch an object before its last legitimate reference is released?
    If something still legitimately holds it when the 5-second check runs, the object is counted as retained even though nothing is wrong. Depending on timing you get a spurious retained count, or a heap dump whose trace points at a reference that was about to be cleared. Watch at the point where nothing should hold the object any more.
  • Can you use the object watcher in a release build without shipping heap dumps?
    Yes. `leakcanary-object-watcher-android` contains `AppWatcher` and the watchers but none of the heap-dumping code. With it as an `implementation` dependency, release builds keep weak references to destroyed objects and expose `retainedObjectCount`, which teams attach to crash reports, while `leakcanary-android` stays debug-only.

  • LeakCanary needs a custom watcher class for every new object type
  • AppWatcher.objectWatcher.watch() is the current, non-deprecated API
  • Calling AppWatcher from main code is fine because LeakCanary is a debug dependency
  • Watching an object as soon as it is created catches leaks earlier
  • leakcanary-object-watcher-android dumps the heap in release builds

Assumes LeakCanary 2.14; expectWeaklyReachable() replaced the deprecated watch() in 2.6, and LeakCanary 1.x's RefWatcher was removed in 2.0.