This repository was archived by the owner on Nov 14, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathBinding.java
More file actions
68 lines (56 loc) · 2.49 KB
/
Binding.java
File metadata and controls
68 lines (56 loc) · 2.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package com.guigarage.binding;
import javax.observer.Observable;
import javax.observer.Property;
import javax.observer.Subscription;
import javax.observer.binding.ConvertableBidirectionalBindable;
import java.util.function.Consumer;
import java.util.function.Function;
/**
* Class that provides basic functionallity for bindings wothout handling any thread issues, etc. This is not thread safe
* and should only be used for Bindings that will be handled on the same Thread.
*/
public class Binding {
private static class InternalConvertableBidirectionalBindable<T> implements ConvertableBidirectionalBindable<T, InternalConvertableBidirectionalBindable<T>> {
private final Property<T> property;
private Consumer<Throwable> errorHandler = e -> e.printStackTrace();
private boolean bindingCalled = false;
public InternalConvertableBidirectionalBindable(Property<T> property) {
this.property = property;
}
@Override
public <U> Subscription bidirectionalTo(Property<U> toProperty, Function<U, T> converter, Function<T, U> converter2) {
Subscription subscription1 = to(toProperty, converter);
Subscription subscription2 = bind(property, toProperty, converter2);
return () -> {
subscription1.unsubscribe();
subscription2.unsubscribe();
};
}
@Override
public <U> Subscription to(Observable<U> observable, Function<U, T> converter) {
return bind(observable, property, converter);
}
private <U, V> Subscription bind(Observable<U> observable, Property<V> property, Function<U, V> converter) {
return observable.onChanged(e -> {
if (!bindingCalled) {
bindingCalled = true;
try {
property.setValue(converter.apply(e.getValue()));
} catch (Exception ex) {
errorHandler.accept(ex);
} finally {
bindingCalled = false;
}
}
});
}
@Override
public InternalConvertableBidirectionalBindable<T> withErrorHandler(Consumer<Throwable> handler) {
this.errorHandler = errorHandler;
return this;
}
}
public static <T> ConvertableBidirectionalBindable<T, ?> bind(Property<T> property) {
return new InternalConvertableBidirectionalBindable<T>(property);
}
}