OLD | NEW |
---|---|
(Empty) | |
1 // Copyright 2016 The Chromium Authors. All rights reserved. | |
2 // Use of this source code is governed by a BSD-style license that can be | |
3 // found in the LICENSE file. | |
4 | |
5 package org.chromium.base; | |
6 | |
7 import android.os.Handler; | |
8 import android.os.Looper; | |
9 | |
10 import java.util.LinkedList; | |
11 import java.util.List; | |
12 | |
13 /** | |
14 * A Promise class to be used as a placeholder for a result that will be provide d asynchronously. | |
15 * It must only be accessed from a single thread. | |
16 * @param <T> The type the Promise will be fulfilled with. | |
17 */ | |
18 public class Promise<T> { | |
19 private T mResult; | |
20 private boolean mFulfilled; | |
21 private final List<Callback<T>> mCallbacks = new LinkedList<Callback<T>>(); | |
22 private final Thread mThread; | |
23 | |
24 /** | |
25 * Creates an unfulfilled promise. | |
26 */ | |
27 public Promise() { | |
28 mThread = Thread.currentThread(); | |
29 } | |
30 | |
31 /** | |
32 * Queues a {@link Callback} to be run when the Promise is fulfilled or runs it | |
33 * instantly if the Promise is already fulfilled. | |
34 */ | |
35 public void then(Callback<T> callback) { | |
36 checkThread(); | |
37 | |
38 if (mFulfilled) { | |
39 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.
| |
40 } else { | |
41 mCallbacks.add(callback); | |
42 } | |
43 } | |
44 | |
45 /** | |
46 * Fulfills the Promise with the result and passes it to any {@link Callback }s | |
47 * previously queued with {@link Promise#then(Callback)}. | |
48 */ | |
49 public void fulfill(final T result) { | |
50 checkThread(); | |
51 assert !mFulfilled; | |
52 | |
53 mFulfilled = true; | |
54 mResult = result; | |
55 for (final Callback<T> callback : mCallbacks) { | |
56 // Post the callbacks to the Thread looper so we don't get a long ch ain of callbacks | |
57 // holding up the thread. | |
58 new Handler(Looper.myLooper()).post(new Runnable() { | |
59 @Override | |
60 public void run() { | |
61 callback.onResult(mResult); | |
62 } | |
63 }); | |
64 } | |
65 mCallbacks.clear(); | |
66 } | |
67 | |
68 /** | |
69 * Convenience method to return a Promise fulfilled with the given result. | |
70 */ | |
71 public static <T> Promise<T> fulfilled(T result) { | |
72 Promise<T> promise = new Promise<T>(); | |
73 promise.fulfill(result); | |
74 return promise; | |
75 } | |
76 | |
77 private void checkThread() { | |
78 assert mThread == Thread.currentThread() : "Promise must only be used on a single Thread."; | |
79 } | |
80 } | |
OLD | NEW |