Skip to content

Commit 4c8c7a0

Browse files
author
nicolaiparlog
committed
'ListenerHandleDemo' now also shows how to attach and detach a listener.
1 parent d9a3a04 commit 4c8c7a0

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

src/demo/java/org/codefx/libfx/listener/handle/ListenerHandleDemo.java

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ public static void main(String[] args) {
3131

3232
demo.createCommonListenerHandle();
3333
demo.createCustomListenerHandle();
34+
demo.attachAndDetach();
3435
}
3536

3637
// #end CONSTRUCTION & MAIN
@@ -76,6 +77,49 @@ private void createCustomListenerHandle() {
7677
handleForCustomClasses.attach();
7778
}
7879

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+
79123
// #end DEMOS
80124

81125
// #region NESTED CLASSES

0 commit comments

Comments
 (0)