android / android/android-test
addLifecycleCallback should hold a strong ref to callbacks.
- Dominant language
- Java
- Stars
- 1.2k
- Forks
- 342
- Avg merge
- 11h 29m
- Merged PRs (30d)
- 2
Description
### Description
(was filed here in 2017: https://issuetracker.google.com/issues/38323394)
This `ActivityLifecycleMonitor.addLifecycleCallback` behavior is really surprising and bites me every few years...
You only notice it when your callbacks are flaky because they are being GC'd...
https://github.com/android/android-test/blob/master/runner/monitor/java/androidx/test/runner/lifecycle/ActivityLifecycleMonitor.java#L40-L42
```
*
Implementors will not hold a strong ref to the callback, the code which registers callbacks
* is responsible for this. Code which registers callbacks should responsibly remove their
* callback when it is no longer needed.
```
**This may never be called at all** and could be instantly GC'd... or it might be called a few times until the GC removes the callback.
```kotlin
ActivityLifecycleMonitorRegistry.getInstance().addLifecycleCallback { activity, stage ->
// do callback stuff
}
```
Have to remember to hold a reference to the callback...
```kotlin
object HoldOnToTheCallback {
val activityLifecycleCallback = ActivityLifecycleCallback { activity, stage ->
// do callback stuff
}
}
// somewhere else
ActivityLifecycleMonitorRegistry.getInstance().addLifecycleCallback(HoldOnToTheCallback.activityLifecycleCallback)
```
Would be great to just change the behavior, or provide a lint warning, or provide a junit rule to hold the callback reference (as suggested on the original ticket).
Contributor guide
Research direction
Start with ActivityLifecycleMonitor.java at the linked addLifecycleCallback documentation and review the original issue for the intended ownership behavior. Compare the proposed strong-reference, lint-warning, and JUnit-rule directions before selecting a scoped approach. Done means the chosen behavior is implemented with coverage showing callbacks are not unexpectedly garbage-collected.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- android, java
- Domain
- mobile, testing
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 25/100