@@ -31,6 +31,7 @@ public static void main(String[] args) {
31
31
32
32
demo .createCommonListenerHandle ();
33
33
demo .createCustomListenerHandle ();
34
+ demo .attachAndDetach ();
34
35
}
35
36
36
37
// #end CONSTRUCTION & MAIN
@@ -76,6 +77,49 @@ private void createCustomListenerHandle() {
76
77
handleForCustomClasses .attach ();
77
78
}
78
79
80
+ // attach & detach
81
+
82
+ /**
83
+ * Demonstrates how to add and remove a listener with a {@link ListenerHandle} and compares this to the normal
84
+ * approach.
85
+ */
86
+ private void attachAndDetach () {
87
+ Property <String > observedProperty = new SimpleStringProperty ("initial value" );
88
+
89
+ // usually a listener is directly added to the property;
90
+ // but if the listener has to be removed later, the reference needs to be stored explicitly
91
+ ChangeListener <Object > changePrintingListener = (obs , oldValue , newValue ) ->
92
+ System .out .println ("[LISTENER] Value changed from \" " + oldValue + "\" to \" " + newValue + "\" ." );
93
+ observedProperty .addListener (changePrintingListener );
94
+
95
+ // this is the alternative with a 'ListenerHandle'
96
+ ListenerHandle newValuePrinter = ListenerHandles .createAttached (observedProperty ,
97
+ (obs , oldValue , newValue ) -> System .out .println ("[HANDLE] New value: \" " + newValue + "\" " ));
98
+
99
+ // now lets change the value to see how it works
100
+ observedProperty .setValue ("new value" );
101
+ observedProperty .setValue ("even newer value" );
102
+
103
+ // removing a listener needs references to both the observable and the listener;
104
+ // depending on the situation this might not be feasible
105
+ observedProperty .removeListener (changePrintingListener );
106
+ // with a handle, the listener can be removed without giving the caller the possibility tp interact with
107
+ // the observable or the listener; it is also a little more readable
108
+ newValuePrinter .detach ();
109
+
110
+ // some unobserved changes...
111
+ observedProperty .setValue ("you won't see this on the console" );
112
+ observedProperty .setValue ("nor this" );
113
+
114
+ // the same as above goes for adding the listener
115
+ observedProperty .addListener (changePrintingListener );
116
+ newValuePrinter .attach ();
117
+
118
+ // now some more changes
119
+ observedProperty .setValue ("but you will see this" );
120
+ observedProperty .setValue ("and this" );
121
+ }
122
+
79
123
// #end DEMOS
80
124
81
125
// #region NESTED CLASSES
0 commit comments