Android - Will memory leak occur if view model contains activity listener reference?

Viewed 869

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
});

}

}
1 Answers

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".

Related