Memory Leak Detection in KMP
Memory leaks in cross-platform mobile apps occur when disposed objects (such as ViewModels, UI controllers, coroutine jobs, or native platform bridges) remain strongly retained in memory by long-lived singletons, callbacks, or static references.
Appxiom provides automated post-dispose memory leak detection across Android and iOS without requiring large, disruptive heap dumps.
1. Watching ViewModels & Objects (Ax.watchLeaks)
Watch any Kotlin object after its lifecycle has concluded:
import tech.appxiom.kmp.Ax
// Basic usage:
Ax.watchLeaks(myDisposedObject)
// With explicit diagnostic tag:
Ax.watchLeaks(target = checkoutViewModel, tag = "CheckoutViewModel")
Example: ViewModel Cleanup
In Android / KMP ViewModels:
import androidx.lifecycle.ViewModel
import tech.appxiom.kmp.Ax
class UserProfileViewModel : ViewModel() {
override fun onCleared() {
super.onCleared()
// Register this instance for post-disposal leak verification:
Ax.watchLeaks(this, tag = "UserProfileViewModel")
}
}
2. Compose Multiplatform Screens (AxWatchLeakOnDispose)
Module: tech.appxiom:appxiom-kmp-compose
In Compose Multiplatform, use AxWatchLeakOnDispose to automatically watch state holders or view models when a Composable leaves the composition:
import androidx.compose.runtime.Composable
import tech.appxiom.kmp.compose.AxWatchLeakOnDispose
@Composable
fun ProductDetailScreen(viewModel: ProductDetailViewModel) {
// Automatically watches viewModel when ProductDetailScreen leaves composition:
AxWatchLeakOnDispose(target = viewModel, tag = "ProductDetailViewModel")
// Screen UI...
}
3. Investigating Leaks in the Dashboard
When a verified memory leak occurs, Appxiom generates an issue report in your dashboard:
- Target Object: Retained class name and assigned tag (e.g.
UserProfileViewModel). - Retained Duration: Time elapsed between disposal and leak verification.
- Occurrence Context: Screen breadcrumbs, active user ID, and device memory state.
Next Steps
Learn how to record user breadcrumbs in Activity Trails & Logging.