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