1 /*
2  * Copyright (C) 2014 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 android.hardware.camera2.dispatch;
17 
18 
19 import java.lang.reflect.Method;
20 import java.util.Arrays;
21 import java.util.List;
22 
23 import static com.android.internal.util.Preconditions.*;
24 
25 /**
26  * Broadcast a single dispatch into multiple other dispatchables.
27  *
28  * <p>Every time {@link #dispatch} is invoked, all the broadcast targets will
29  * see the same dispatch as well. The first target's return value is returned.</p>
30  *
31  * <p>This enables a single listener to be converted into a multi-listener.</p>
32  */
33 public class BroadcastDispatcher<T> implements Dispatchable<T> {
34 
35     private final List<Dispatchable<T>> mDispatchTargets;
36 
37     /**
38      * Create a broadcast dispatcher from the supplied dispatch targets.
39      *
40      * @param dispatchTargets one or more targets to dispatch to
41      */
42     @SafeVarargs
BroadcastDispatcher(Dispatchable<T>.... dispatchTargets)43     public BroadcastDispatcher(Dispatchable<T>... dispatchTargets) {
44         mDispatchTargets = Arrays.asList(
45                 checkNotNull(dispatchTargets, "dispatchTargets must not be null"));
46     }
47 
48     @Override
dispatch(Method method, Object[] args)49     public Object dispatch(Method method, Object[] args) throws Throwable {
50         Object result = null;
51         boolean gotResult = false;
52 
53         for (Dispatchable<T> dispatchTarget : mDispatchTargets) {
54             Object localResult = dispatchTarget.dispatch(method, args);
55 
56             if (!gotResult) {
57                 gotResult = true;
58                 result = localResult;
59             }
60         }
61 
62         return result;
63     }
64 }
65