1 /* 2 * Copyright (C) 2021 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.server.wm.jetpack.utils; 18 19 import androidx.annotation.Nullable; 20 import androidx.window.extensions.core.util.function.Consumer; 21 22 import java.util.concurrent.LinkedBlockingQueue; 23 import java.util.concurrent.TimeUnit; 24 25 /** 26 * Consumer that provides a simple way to wait for a specific count of values to be received within 27 * a timeout and then return the last value. 28 * 29 * It requires the vendor API version at least {@link ExtensionUtil#EXTENSION_VERSION_2} because 30 * it uses extensions core version of {@link Consumer} instead of 31 * {@link java.util.function.Consumer Java 8 version Consumer}. 32 */ 33 public class TestValueCountConsumer<T> implements Consumer<T> { 34 35 private static final long TIMEOUT_MS = 3000; 36 private static final int DEFAULT_COUNT = 1; 37 private int mCount = DEFAULT_COUNT; 38 private LinkedBlockingQueue<T> mLinkedBlockingQueue; 39 private T mLastReportedValue; 40 TestValueCountConsumer()41 public TestValueCountConsumer() { 42 mLinkedBlockingQueue = new LinkedBlockingQueue<>(); 43 } 44 45 @Override accept(T value)46 public void accept(T value) { 47 // Asynchronously offer value to queue 48 mLinkedBlockingQueue.offer(value); 49 } 50 setCount(int count)51 public void setCount(int count) { 52 mCount = count; 53 } 54 55 @Nullable waitAndGet()56 public T waitAndGet() throws InterruptedException { 57 T value = null; 58 for (int i = 0; i < mCount; i++) { 59 value = mLinkedBlockingQueue.poll(TIMEOUT_MS, TimeUnit.MILLISECONDS); 60 } 61 mLastReportedValue = value; 62 return value; 63 } 64 65 // Doesn't change the count. clearQueue()66 public void clearQueue() { 67 mLinkedBlockingQueue.clear(); 68 } 69 70 @Nullable getLastReportedValue()71 public T getLastReportedValue() { 72 return mLastReportedValue; 73 } 74 } 75