Index: base/android/java/src/org/chromium/base/Promise.java |
diff --git a/base/android/java/src/org/chromium/base/Promise.java b/base/android/java/src/org/chromium/base/Promise.java |
new file mode 100644 |
index 0000000000000000000000000000000000000000..32296761ecc8a213b5e832d00953d27afb714186 |
--- /dev/null |
+++ b/base/android/java/src/org/chromium/base/Promise.java |
@@ -0,0 +1,80 @@ |
+// Copyright 2016 The Chromium Authors. All rights reserved. |
+// Use of this source code is governed by a BSD-style license that can be |
+// found in the LICENSE file. |
+ |
+package org.chromium.base; |
+ |
+import android.os.Handler; |
+import android.os.Looper; |
+ |
+import java.util.LinkedList; |
+import java.util.List; |
+ |
+/** |
+ * A Promise class to be used as a placeholder for a result that will be provided asynchronously. |
+ * It must only be accessed from a single thread. |
+ * @param <T> The type the Promise will be fulfilled with. |
+ */ |
+public class Promise<T> { |
+ private T mResult; |
+ private boolean mFulfilled; |
+ private final List<Callback<T>> mCallbacks = new LinkedList<Callback<T>>(); |
+ private final Thread mThread; |
+ |
+ /** |
+ * Creates an unfulfilled promise. |
+ */ |
+ public Promise() { |
+ mThread = Thread.currentThread(); |
+ } |
+ |
+ /** |
+ * Queues a {@link Callback} to be run when the Promise is fulfilled or runs it |
+ * instantly if the Promise is already fulfilled. |
+ */ |
+ public void then(Callback<T> callback) { |
+ checkThread(); |
+ |
+ if (mFulfilled) { |
+ callback.onResult(mResult); |
Bernhard Bauer
2016/04/13 16:24:21
I think you may also want want to run this callbac
PEConn
2016/05/25 09:52:12
Done.
|
+ } else { |
+ mCallbacks.add(callback); |
+ } |
+ } |
+ |
+ /** |
+ * Fulfills the Promise with the result and passes it to any {@link Callback}s |
+ * previously queued with {@link Promise#then(Callback)}. |
+ */ |
+ public void fulfill(final T result) { |
+ checkThread(); |
+ assert !mFulfilled; |
+ |
+ mFulfilled = true; |
+ mResult = result; |
+ for (final Callback<T> callback : mCallbacks) { |
+ // Post the callbacks to the Thread looper so we don't get a long chain of callbacks |
+ // holding up the thread. |
+ new Handler(Looper.myLooper()).post(new Runnable() { |
+ @Override |
+ public void run() { |
+ callback.onResult(mResult); |
+ } |
+ }); |
+ } |
+ mCallbacks.clear(); |
+ } |
+ |
+ /** |
+ * Convenience method to return a Promise fulfilled with the given result. |
+ */ |
+ public static <T> Promise<T> fulfilled(T result) { |
+ Promise<T> promise = new Promise<T>(); |
+ promise.fulfill(result); |
+ return promise; |
+ } |
+ |
+ private void checkThread() { |
+ assert mThread == Thread.currentThread() : "Promise must only be used on a single Thread."; |
+ } |
+} |