I'm injecting an @ActivityRetainedScoped
component via Hilt. The component is registering a listener so I want to make sure it cleans up after itself and doesn't leak anything.
I have seen ActivityRetainedLifecycle.OnClearedListener
in the JavaDocs for Hilt but haven't seen any examples of how to use it.
E.g. using WifiManager as an example, at the moment I'm doing this:
@ActivityRetainedScoped
public class Wifi {
@Inject
public Wifi(
@NonNull final Application application,
@NonNull final ActivityRetainedLifecycle activityRetainedLifecycle,
@NonNull final WifiManager wifiManager
) {
final Context applicationContext = application.getApplicationContext();
final IntentFilter intentFilter = /* Init intentFilter */
final WifiScanReceiver wifiScanReceiver = /* Init wifiScanReceiver */
applicationContext.registerReceiver(wifiScanReceiver, intentFilter);
activityRetainedLifecycle.addOnClearedListener(() -> {
applicationContext.unregisterReceiver(wifiScanReceiver);
});
}
}
It feels self-explanatory but I've been burned by assuming stuff like this before and can't find much online to validate my assumption on it.
Is that the correct way to 'tear down' an activity-retained component that has external dependencies to make sure it doesn't leak?