Observable.java revision 54b6cfa9a9e5b861a9930af873580d6dc20f773c
1/*
2 * Copyright (C) 2007 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
17package android.database;
18
19import java.util.ArrayList;
20
21/**
22 * Provides methods for (un)registering arbitrary observers in an ArrayList.
23 */
24public abstract class Observable<T> {
25    /**
26     * The list of observers.  An observer can be in the list at most
27     * once and will never be null.
28     */
29    protected final ArrayList<T> mObservers = new ArrayList<T>();
30
31    /**
32     * Adds an observer to the list. The observer cannot be null and it must not already
33     * be registered.
34     * @param observer the observer to register
35     * @throws IllegalArgumentException the observer is null
36     * @throws IllegalStateException the observer is already registered
37     */
38    public void registerObserver(T observer) {
39        if (observer == null) {
40            throw new IllegalArgumentException("The observer is null.");
41        }
42        synchronized(mObservers) {
43            if (mObservers.contains(observer)) {
44                throw new IllegalStateException("Observer " + observer + " is already registered.");
45            }
46            mObservers.add(observer);
47        }
48    }
49
50    /**
51     * Removes a previously registered observer. The observer must not be null and it
52     * must already have been registered.
53     * @param observer the observer to unregister
54     * @throws IllegalArgumentException the observer is null
55     * @throws IllegalStateException the observer is not yet registered
56     */
57    public void unregisterObserver(T observer) {
58        if (observer == null) {
59            throw new IllegalArgumentException("The observer is null.");
60        }
61        synchronized(mObservers) {
62            int index = mObservers.indexOf(observer);
63            if (index == -1) {
64                throw new IllegalStateException("Observer " + observer + " was not registered.");
65            }
66            mObservers.remove(index);
67        }
68    }
69
70    /**
71     * Remove all registered observer
72     */
73    public void unregisterAll() {
74        synchronized(mObservers) {
75            mObservers.clear();
76        }
77    }
78}
79