1 /* 2 * Copyright 2018 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.car.arch.common.testing; 18 19 20 import androidx.annotation.Nullable; 21 import androidx.annotation.RestrictTo; 22 import androidx.lifecycle.Observer; 23 24 25 /** 26 * An Observer that retains its most recently observed value 27 * 28 * @param <T> the type to be observed 29 */ 30 @RestrictTo(RestrictTo.Scope.TESTS) 31 public class CaptureObserver<T> implements Observer<T> { 32 33 private boolean mNotified = false; 34 private T mValue; 35 36 /** 37 * Returns {@code true} iff {@link #onChanged(T)} has been called with any value (including 38 * {@code 39 * null}). 40 */ hasBeenNotified()41 public boolean hasBeenNotified() { 42 return mNotified; 43 } 44 45 /** 46 * Returns the most recently observed value (may be {@code null}). Returns {@code null} if no 47 * value has been observed. 48 * 49 * @see #hasBeenNotified() 50 */ 51 @Nullable getObservedValue()52 public T getObservedValue() { 53 return mValue; 54 } 55 56 @Override onChanged(@ullable T t)57 public void onChanged(@Nullable T t) { 58 mNotified = true; 59 mValue = t; 60 } 61 62 /** 63 * Resets this CaptureObserver to its inital state. {@link #hasBeenNotified()} will return 64 * {@code 65 * false} and {@link #getObservedValue()} will return {@code null}. 66 */ reset()67 public void reset() { 68 mValue = null; 69 mNotified = false; 70 } 71 } 72