1 /*
2  * Copyright (C) 2015 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.camera.async;
18 
19 import com.android.camera.util.Callback;
20 
21 import java.util.concurrent.Executor;
22 
23 import javax.annotation.ParametersAreNonnullByDefault;
24 import javax.annotation.concurrent.ThreadSafe;
25 
26 /**
27  * Wraps a not-necessarily-thread-safe callback into a thread-safe callback
28  * which runs it on an executor.
29  */
30 @ThreadSafe
31 @ParametersAreNonnullByDefault
32 public class ExecutorCallback<T> implements Updatable<T> {
33     private final Callback<T> mCallback;
34     private final Executor mExecutor;
35 
36     /**
37      * @param callback The callback to wrap.
38      * @param executor The executor on which to invoke the callback.
39      */
ExecutorCallback(Callback<T> callback, Executor executor)40     public ExecutorCallback(Callback<T> callback, Executor executor) {
41         mCallback = callback;
42         mExecutor = executor;
43     }
44 
45     @Override
update(final T t)46     public void update(final T t) {
47         mExecutor.execute(new Runnable() {
48             @Override
49             public void run() {
50                 mCallback.onCallback(t);
51             }
52         });
53     }
54 }
55