main

square/leakcanary

Last updated at: 29/12/2023 09:39

LeakCanaryDelegate.kt

TLDR

This file contains the LeakCanaryDelegate object, which is responsible for loading and executing the LeakCanary library in an Android application.

Classes

LeakCanaryDelegate

The LeakCanaryDelegate is an internal object that provides a lazy property loadLeakCanary for loading and executing the LeakCanary library in an Android application. It uses reflection to load the InternalLeakCanary class and obtains the INSTANCE field value, which is a lambda function (Application) -> Unit. If the loading process fails, it falls back to the NoLeakCanary object.

NoLeakCanary

The NoLeakCanary object is a fallback implementation of the (Application) -> Unit lambda function. It does nothing when invoked and implements the OnObjectRetainedListener interface, which has an empty onObjectRetained method.

package leakcanary.internal

import android.app.Application
import leakcanary.OnObjectRetainedListener

internal object LeakCanaryDelegate {

  @Suppress("UNCHECKED_CAST")
  val loadLeakCanary by lazy {
    try {
      val leakCanaryListener = Class.forName("leakcanary.internal.InternalLeakCanary")
      leakCanaryListener.getDeclaredField("INSTANCE")
        .get(null) as (Application) -> Unit
    } catch (ignored: Throwable) {
      NoLeakCanary
    }
  }

  object NoLeakCanary : (Application) -> Unit, OnObjectRetainedListener {
    override fun invoke(application: Application) {
    }

    override fun onObjectRetained() {
    }
  }
}