1 /*
2  * Copyright (C) 2015 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package android.databinding;
17 
18 import java.io.Serializable;
19 
20 /**
21  * An object wrapper to make it observable.
22  * <p>
23  * Observable field classes may be used instead of creating an Observable object:
24  * <pre><code>public class MyDataObject {
25  *     public final ObservableField&lt;String&gt; name = new ObservableField&lt;String&gt;();
26  *     public final ObservableInt age = new ObservableInt();
27  * }</code></pre>
28  * Fields of this type should be declared final because bindings only detect changes in the
29  * field's value, not of the field itself.
30  *
31  * @param <T> The type parameter for the actual object.
32  * @see android.databinding.ObservableParcelable
33  */
34 public class ObservableField<T> extends BaseObservable implements Serializable {
35     static final long serialVersionUID = 1L;
36     private T mValue;
37 
38     /**
39      * Wraps the given object and creates an observable object
40      *
41      * @param value The value to be wrapped as an observable.
42      */
ObservableField(T value)43     public ObservableField(T value) {
44         mValue = value;
45     }
46 
47     /**
48      * Creates an empty observable object
49      */
ObservableField()50     public ObservableField() {
51     }
52 
53     /**
54      * @return the stored value.
55      */
get()56     public T get() {
57         return mValue;
58     }
59 
60     /**
61      * Set the stored value.
62      */
set(T value)63     public void set(T value) {
64         if (value != mValue) {
65             mValue = value;
66             notifyChange();
67         }
68     }
69 }
70