]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/model/ObservableValue.java
another major rework, transaction list is fully asynchronous
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / model / ObservableValue.java
1 /*
2  * Copyright © 2019 Damyan Ivanov.
3  * This file is part of Mobile-Ledger.
4  * Mobile-Ledger is free software: you can distribute it and/or modify it
5  * under the term of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your opinion), any later version.
8  *
9  * Mobile-Ledger is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  * GNU General Public License terms for details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with Mobile-Ledger. If not, see <https://www.gnu.org/licenses/>.
16  */
17
18 package net.ktnx.mobileledger.model;
19
20 import java.util.Observable;
21 import java.util.Observer;
22
23 public class ObservableValue<T> {
24     private final ObservableValueImpl<T> impl = new ObservableValueImpl<>();
25     public ObservableValue() {}
26     public ObservableValue(T initialValue) {
27         impl.setValue(initialValue, false);
28     }
29     public void set(T newValue) {
30         impl.setValue(newValue);
31     }
32     public T get() {
33         return impl.getValue();
34     }
35     public void addObserver(Observer o) {
36         impl.addObserver(o);
37     }
38     public void deleteObserver(Observer o) {
39         impl.deleteObserver(o);
40     }
41     public void notifyObservers() {
42         impl.notifyObservers();
43     }
44     public void notifyObservers(Object arg) {
45         impl.notifyObservers(arg);
46     }
47     public void deleteObservers() {
48         impl.deleteObservers();
49     }
50     public boolean hasChanged() {
51         return impl.hasChanged();
52     }
53     public int countObservers() {
54         return impl.countObservers();
55     }
56     private class ObservableValueImpl<T> extends Observable {
57         protected T value;
58         public void setValue(T newValue) {
59             setValue(newValue, true);
60         }
61         private synchronized void setValue(T newValue, boolean notify) {
62             if (newValue.equals(value)) return;
63
64             T oldValue = value;
65             value = newValue;
66             setChanged();
67             if (notify) notifyObservers(oldValue);
68         }
69         public T getValue() {
70             return value;
71         }
72     }
73 }