1

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?

anotherdave
  • 6,656
  • 4
  • 34
  • 65

1 Answers1

0

Yes, according to the documentation.

And Thanks! I found it thanks to your question.

Interestingly it also explains the mechanics of it

Specifically this will be invoked during Activity.onDestroy() when Activity.isChangingConfigurations() is false.

Yuri Schimke
  • 12,435
  • 3
  • 35
  • 69