FilteredUpdatable.java revision 9c94ab32a69a1ad3642a0f1e38e68bcfd97d3511
1/* 2 * Copyright (C) 2014 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 com.android.camera.async; 18 19/** 20 * Wraps an {@link com.android.camera.async.Updatable} by filtering out 21 * duplicate updates. 22 */ 23public class FilteredUpdatable<T> implements Updatable<T> { 24 private final Updatable<T> mUpdatable; 25 private final Object mLock; 26 private boolean mValueSet; 27 private T mLatestValue; 28 29 public FilteredUpdatable(Updatable<T> updatable) { 30 mUpdatable = updatable; 31 mLock = new Object(); 32 mValueSet = false; 33 mLatestValue = null; 34 } 35 36 @Override 37 public void update(T t) { 38 synchronized (mLock) { 39 if (!mValueSet) { 40 setNewValue(t); 41 } else { 42 if (t == null && mLatestValue != null) { 43 setNewValue(t); 44 } else if (t != null) { 45 if (!t.equals(mLatestValue)) { 46 setNewValue(t); 47 } 48 } 49 } 50 } 51 } 52 53 private void setNewValue(T value) { 54 synchronized (mLock) { 55 mUpdatable.update(value); 56 mLatestValue = value; 57 mValueSet = true; 58 } 59 } 60} 61