Skip to content

Commit 069d75d

Browse files
committed
memory leak fix
1 parent 9437cde commit 069d75d

File tree

1 file changed

+12
-3
lines changed

1 file changed

+12
-3
lines changed

location/src/main/kotlin/io/customer/location/LocationLifecycleObserver.kt

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package io.customer.location
22

33
import androidx.lifecycle.DefaultLifecycleObserver
44
import androidx.lifecycle.LifecycleOwner
5+
import java.lang.ref.WeakReference
56

67
/**
78
* Manages location lifecycle tied to app foreground/background transitions.
@@ -11,25 +12,33 @@ import androidx.lifecycle.LifecycleOwner
1112
* when [trackingMode] is [LocationTrackingMode.ON_APP_START].
1213
* - [onStop]: cancels any in-flight GPS request when the app enters background.
1314
*
15+
* Uses a [WeakReference] to [LocationServicesImpl] so that [ProcessLifecycleOwner]
16+
* (which lives for the entire process) does not prevent SDK cleanup. When the SDK
17+
* is reset via [CustomerIO.clearInstance], the services become eligible for GC,
18+
* the weak reference clears, and this observer becomes a no-op.
19+
*
1420
* Thread safety: all lifecycle callbacks are delivered on the main thread
1521
* by [ProcessLifecycleOwner], so no synchronization is needed.
1622
*/
1723
internal class LocationLifecycleObserver(
18-
private val locationServices: LocationServicesImpl,
24+
locationServices: LocationServicesImpl,
1925
private val trackingMode: LocationTrackingMode
2026
) : DefaultLifecycleObserver {
2127

28+
private val servicesRef = WeakReference(locationServices)
2229
private var hasRequestedOnStart = false
2330

2431
override fun onStart(owner: LifecycleOwner) {
32+
val services = servicesRef.get() ?: return
2533
if (trackingMode == LocationTrackingMode.ON_APP_START && !hasRequestedOnStart) {
2634
hasRequestedOnStart = true
27-
locationServices.requestLocationUpdate()
35+
services.requestLocationUpdate()
2836
}
2937
}
3038

3139
override fun onStop(owner: LifecycleOwner) {
32-
val wasCancelled = locationServices.cancelInFlightRequest()
40+
val services = servicesRef.get() ?: return
41+
val wasCancelled = services.cancelInFlightRequest()
3342
// If the GPS request was still in flight when we backgrounded,
3443
// allow onStart to retry on the next foreground entry.
3544
if (wasCancelled) {

0 commit comments

Comments
 (0)