| 69 | |
| 70 | template <typename T> |
| 71 | Future<T> add(const lambda::function<Future<T>()>& callback) |
| 72 | { |
| 73 | // This is the future that is used to notify the next callback |
| 74 | // (denoted by 'N' in the following graph). |
| 75 | Owned<Promise<Nothing>> notifier(new Promise<Nothing>()); |
| 76 | |
| 77 | // This is the future that will be returned to the user (denoted |
| 78 | // by 'F' in the following graph). |
| 79 | Owned<Promise<T>> promise(new Promise<T>()); |
| 80 | |
| 81 | // We use a graph to show how we hook these futures. Each box in |
| 82 | // the graph represents a future. As mentioned above, 'F' denotes |
| 83 | // a future that will be returned to the user, and 'N' denotes a |
| 84 | // future that is used for notifying the next callback. Each arrow |
| 85 | // represents a "notification" relation. We will explain in detail |
| 86 | // what "notification" means in the following. |
| 87 | // |
| 88 | // 'last' 'last' 'last' |
| 89 | // | | | |
| 90 | // v v v |
| 91 | // +---+ +---+ +---+ +---+ +---+ +---+ |
| 92 | // | N | | N |--+ | N | | N |--+ | N |--+ | N | |
| 93 | // +---+ +---+ | +---+ +---+ | +---+ | +---+ |
| 94 | // ==> | ^ ==> | ^ | ^ |
| 95 | // | | | | | | |
| 96 | // | +---+ | +---+ | +---+ |
| 97 | // +-->| F | +-->| F | +-->| F | |
| 98 | // +---+ +---+ +---+ |
| 99 | // |
| 100 | // Initial => Added one callback => Added two callbacks. |
| 101 | |
| 102 | // Setup the "notification" from 'F' to 'N' so that when a |
| 103 | // callback is done, signal the notifier ('N'). |
| 104 | promise->future().onAny(lambda::bind(&completed, notifier)); |
| 105 | |
| 106 | // Setup the "notification" from previous 'N' to 'F' so that when |
| 107 | // a notifier ('N') is set (indicating the previous callback has |
| 108 | // completed), invoke the next callback ('F') in the sequence. |
| 109 | last.onAny(lambda::bind(¬ified<T>, promise, callback)); |
| 110 | |
| 111 | // In the following, we setup the hooks so that if this sequence |
| 112 | // process is being terminated, all pending callbacks will be |
| 113 | // discarded. We use weak futures here to avoid cyclic dependencies. |
| 114 | |
| 115 | // Discard the future associated with this notifier. |
| 116 | // |
| 117 | // NOTE: When we discard the notifier future, any `onDiscard()` callbacks |
| 118 | // registered on `promise->future` will be invoked, but `onDiscard` |
| 119 | // callbacks registered on the future returned by `add()` will NOT be |
| 120 | // invoked. This is because currently discards do not propagate through |
| 121 | // `dispatch()`. In other words, users should be careful when registering |
| 122 | // `onDiscard` callbacks on the returned future. |
| 123 | // |
| 124 | // TODO(*): Propagate `onDiscard` through `dispatch`. |
| 125 | notifier->future().onDiscard( |
| 126 | lambda::bind( |
| 127 | &internal::discard<T>, |
| 128 | WeakFuture<T>(promise->future()))); |