-
Notifications
You must be signed in to change notification settings - Fork 104
Lifecycle handling
Views in UI applications have a lifecycle. Typically this lifecycle consists of the following events:
- View is created
- View is added to the applications
- View is removed from the application
- View object is destroyed/garbage collected
In some situations it's useful to be able to react to these events. Event 1 (Creation) is easy in JavaFX. Just put the code into the constructor or the initialize
method of the View.
The other event's aren't as easy to implement. With mvvmFX lifecycle handling it is possible to react to events 2 (View added) and 3 (View removed).
The main usage of lifecycle methods is to react on when the View is removed from the application and to execute cleanup code before the View is garbage collected. Most of the time the necessity for this is that listeners or other code dependencies are preventing the view from being available for garbage collection which can result in memory leaks.
With version 1.6 of mvvmFX a new lifecycle interface SceneLifecycle
was introduced. This interface can be implemented by ViewModels like this:
public class MyViewModel implements ViewModel, SceneLifecycle {
@Override
public void onViewAdded() {
System.out.println("ViewModel added");
}
@Override
public void onViewRemoved() {
System.out.println("ViewModel removed");
}
}
The onViewAdded
method will be invoked when the View that this ViewModel belongs to is added to JavaFX's SceneGraph. Similarly, the onViewRemoved
method will be invoked after the View that this ViewModel belongs to is removed from the SceneGraph. You can use this method to do cleanup before the ViewModel is garbage collected.
At the moment this feature is only available for ViewModels of FXML based Views. It's not supported for CodeBehind/View classes and for ViewModels that belong to a Java based View. In the future we are planning to add lifecycles for these situations too (see issues #470 and #471)