0

Having a fragment, it has a listener which is registered in a global event manager and removed from it when the fragment is destroyed.

In the event listener it calls the fragment's member function foo(), which does some ui update.

So the fragment holds the listener as its member, and listener implicitly holds its container class - fragment. And the listener is temporarily held by event manager until removed from it.

The leak canary reports it is a leak, but the android studio's device monitor does not report it.

Seems this is very commonly used pattern, is it a leak? If it is what is better practice for case like this?

class FooFragment {

public FooFragment() {
   Globals.EventManager.addEventListener(mDataReadyLoadedEventListener);
}

public void dispose() {
   Globals.EventManager.removeEventListener(mDataReadyLoadedEventListener);
   mDataReadyLoadedEventListener = null;
}

... ...

void foo();

EventListener<DataReadyLoadedEvent> mDataReadyLoadedEventListener = new EventListener<DataReadyLoadedEvent>(
        DataReadyLoadedEvent.class) {
    @Override
    public boolean onEvent(DataReadyLoadedEvent event) {

        foo();

        return false;
    }
};
lannyf
  • 9,865
  • 12
  • 70
  • 152

1 Answers1

0

Given the code snippet you've given us we can see where you are doing your cleanup or what may be calling dispose().

You can ensure that cleanup is taking place on the fragment by overriding something like onDestroyView() or onDetach() in the FooFragment class (assuming it extends from the Fragment class which isn't shown above).

Numan1617
  • 1,158
  • 5
  • 19
  • Thanks Numan! the snippet does not show all the details, the dispose is meant to be called at OnDestroyView() of the fragment. – lannyf Nov 03 '16 at 11:49