3

ViewModel has a reference to a listener defined in the activity. Now when the device orientation is changed, will memory leak occur?

Code:

public class MainVM extends ViewModel {

private Listener listener;

public void setListener(Listener listener) {
this.listener = listener;
}

...
}
public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

MainVM mainVM = new ViewModelProvider(this).get(MainVM.class);

mainVM.setListener(new Listener() {
//methods
});

}

}
ApkPro
  • 33
  • 3
  • It depends if your listener holds any reference to activity itself, but generally this is not a good idea and most likely leak. – Pawel Sep 02 '20 at 22:23

1 Answers1

-2

Usually not. This is the reference graph when you create the first activity.

Android --> mainActivity1 --> mainVM1 --> listener1

When you rotate the phone the first activity is destroyed and a new one is created.

            mainActivity1 --> mainVM1 --> listener1
Android --> mainActivity2 --> mainVM2 --> listener2

Because there are not root pointers to you mainActivity1, it can be garbage collected. The same would be true even if mainVM1 or listener1 point back to mainActivity1.

It would be no longer true if mainVM1 has pointers to mainActivity1 AND there is a root pointer to mainVM1, which would keep it alive.

The issue is not "there is something pointing to my activity" but "there is something pointing to my activity which lives much longer then the activity itself".

corradolab
  • 718
  • 3
  • 16
  • 1
    `mainVM2` in your sample doesn't exist as `ViewModelProvider` will return existing viewmodel instance after rotation. In that case new listener will overwrite old one in `mainVM1`. Practically it will prevent `mainActivity1` from leaking but good practice with lifecycle aware components like activity is to clean up all references to it as soon as they become destroyed. – Pawel Sep 02 '20 at 23:08
  • If configuration changes, ViewModel doesn't affect i.e. same view model will be used for activity/fragment. – Mohit Rajput May 17 '21 at 13:41