1 /*
2  * Copyright (C) 2023 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.telecom.cts.apps;
18 
19 import android.os.OutcomeReceiver;
20 import android.telecom.CallException;
21 import android.util.Log;
22 
23 import androidx.annotation.NonNull;
24 
25 import java.util.concurrent.CountDownLatch;
26 
27 /**
28  * LatchedOutcomeReceiver is an implementation of {@link OutcomeReceiver}.  It allows a client to
29  * wrap an OutcomeReceiver with a CountDownLatch so that the client can ensure the outcome was
30  * completed. Be aware that the client should define which outcome they're expecting and assert
31  * appropriately via the wasSuccessful method.
32  */
33 public class LatchedOutcomeReceiver implements OutcomeReceiver<Void, CallException> {
34     private static final String TAG = LatchedOutcomeReceiver.class.getSimpleName();
35     private final CountDownLatch mCountDownLatch;
36     private boolean mWasSuccessful = false;
37     private CallException mCallException = null;
38 
wasSuccessful()39     public boolean wasSuccessful() {
40         return mWasSuccessful;
41     }
42 
getmCallException()43     public CallException getmCallException() {
44         return mCallException;
45     }
46 
LatchedOutcomeReceiver(CountDownLatch latch)47     public LatchedOutcomeReceiver(CountDownLatch latch) {
48         mCountDownLatch = latch;
49     }
50 
51     @Override
onResult(Void result)52     public void onResult(Void result) {
53         Log.i(TAG, "onResult: latch is counting down");
54         mWasSuccessful = true;
55         mCountDownLatch.countDown();
56     }
57 
58     @Override
onError(@onNull CallException error)59     public void onError(@NonNull CallException error) {
60         Log.i(TAG, String.format("onError: code=[%s]", error));
61         mCallException = error;
62         mCountDownLatch.countDown();
63     }
64 }
65