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