1 /* 2 * Copyright (C) 2024 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 androidx.window.extensions.util; 17 18 import androidx.annotation.GuardedBy; 19 import androidx.annotation.NonNull; 20 import androidx.annotation.Nullable; 21 import androidx.window.extensions.core.util.function.Consumer; 22 23 /** 24 * A utility class that will not report a value if it is the same as the last reported value. 25 * @param <T> generic values to be reported. 26 */ 27 public class DeduplicateConsumer<T> implements Consumer<T> { 28 29 private final Object mLock = new Object(); 30 @GuardedBy("mLock") 31 @Nullable 32 private T mLastReportedValue = null; 33 @NonNull 34 private final Consumer<T> mConsumer; 35 DeduplicateConsumer(@onNull Consumer<T> consumer)36 public DeduplicateConsumer(@NonNull Consumer<T> consumer) { 37 mConsumer = consumer; 38 } 39 40 /** 41 * Returns {@code true} if the given consumer matches this object or the wrapped 42 * {@link Consumer}, {@code false} otherwise 43 */ matchesConsumer(@onNull Consumer<T> consumer)44 public boolean matchesConsumer(@NonNull Consumer<T> consumer) { 45 return consumer == this || mConsumer.equals(consumer); 46 } 47 48 /** 49 * Accepts a new value and relays it if it is different from 50 * the last reported value. 51 * @param value to report if different. 52 */ 53 @Override accept(@onNull T value)54 public void accept(@NonNull T value) { 55 synchronized (mLock) { 56 if (mLastReportedValue != null && mLastReportedValue.equals(value)) { 57 return; 58 } 59 mLastReportedValue = value; 60 } 61 mConsumer.accept(value); 62 } 63 } 64