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