├── .gitignore ├── LICENSE ├── README.md ├── docs └── QtPromise-MunichMeetup-20170523.pdf ├── example ├── example.pro ├── main.cpp ├── promiseexample.cpp └── promiseexample.h ├── promise.h ├── promise.pro └── tests ├── promisetests.cpp ├── promisetests.h └── tests.pro /.gitignore: -------------------------------------------------------------------------------- 1 | # Qt 2 | *.pro.user 3 | *.pro.user.* 4 | *.qbs.user 5 | *.qbs.user.* 6 | 7 | # QtCreator 8 | *.autosave 9 | 10 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## QtPromise - Chainable promises for Qt 2 | 3 | Introduction 4 | ======== 5 | 6 | Why promises? 7 | - Promises make asynchronous operations easier to write 8 | - No code fragmentation (compared to separate "slot" methods or nested callbacks) 9 | - More efficient code by encouraging developers to implement asynchronous operations 10 | without additional complexity 11 | - Error handling 12 | - Safer code with a clear scope and context variables 13 | 14 | Why QtPromise? 15 | - Easy to use API for promises 16 | - Integration with Qt event loops 17 | - Define a context for variables used within a promise chain 18 | - Limit the lifetime of the promise (e.g. stop when a given QObject has been destroyed) 19 | - Support for QObject connect 20 | - Support for QThread/QThreadPool 21 | - Compatibility with QtConcurrent/QFuture 22 | 23 | 24 | Features 25 | ======== 26 | 27 | **1. Basic concept** 28 | 29 | A promise has: 30 | - a status (pending, fulfilled, failed, canceled) 31 | - a value (set when it has been fulfilled) 32 | - the possibility to be chained with another promise ('then') 33 | 34 | *How to create promises?* 35 | 36 | Create a fulfilled promise with a value: 37 | ```c++ 38 | auto promise1 = Promise(); 39 | auto promise2 = Promise(true); 40 | auto promise3 = Promise("stringValue"); 41 | ``` 42 | 43 | Chain an existing promise with 'Promise::then()': 44 | ```c++ 45 | auto promise = Promise().then([]() { 46 | // resolve promise: 47 | return value; 48 | 49 | // or reject promise: 50 | throw(PromiseError(msg)); 51 | }); 52 | ``` 53 | 54 | Call 'makePromise()' (c++14 only!): 55 | ```c++ 56 | auto promise = makePromise([](auto resolve, auto reject) { 57 | // resolve promise... 58 | resolve(value); 59 | 60 | // ...or reject promise 61 | reject(PromiseError(msg)); 62 | }); 63 | ``` 64 | 65 | Use a 'Deferred': 66 | ```c++ 67 | Deferred defer; 68 | auto promise = defer.promise(); 69 | 70 | // resolve promise... 71 | defer.resolve(value); 72 | 73 | // ...or reject promise: 74 | defer.reject(PromiseError(msg)); 75 | }); 76 | ``` 77 | 78 | **2. Promise chains** 79 | 80 | Promises are chained using the 'Promise::then()' method. After the current promise has been resolved, the 81 | lambda is called with the promise value as (optional) parameter and a new promise is returned. 82 | 83 | By default, the promise chain is running in the Qt event loop of the current thread and the successive 84 | operations are queued. 85 | 86 | Example of promise chain without error: 87 | ```c++ 88 | Promise promise = Promise() 89 | .then([]() { 90 | // executed in the next step of the current event loop 91 | // resolved without value 92 | }) 93 | .then([]() { 94 | // executed in the next step of the current event loop 95 | return 12; 96 | }) 97 | .fail([](const PromiseError &error) { 98 | // not executed because there was no error 99 | // Note: the returned promise is still fulfilled with the above value 100 | }) 101 | .finally([]() { 102 | // always executed 103 | // Note: the returned promise is still fulfilled with the above value 104 | }) 105 | 106 | promise 107 | .then([](int value) { 108 | // Executed with value == 12 109 | }); 110 | ``` 111 | 112 | Example of promise chain with an error: 113 | ```c++ 114 | Promise promise = Promise() 115 | .then([]() { 116 | // executed in the next step of the current event loop 117 | throw PromiseError("This is an error"); 118 | }) 119 | .then([]() { 120 | // not reached because of the previous error 121 | return 12; 122 | }) 123 | .fail([](const PromiseError &error) { 124 | // executed because of the above error 125 | // (error.message() == "This is an error") 126 | // Note: the returned promise is still failed with the above error 127 | // unless we return here a new Promise 128 | }) 129 | .finally([]() { 130 | // always executed 131 | // Note: the returned promise is still failed with the above error 132 | }) 133 | 134 | promise 135 | .then([](int value) { 136 | // not executed because the previous promise has failed 137 | }) 138 | .then([](const PromiseError &error) { 139 | // executed because the previous promise failed 140 | // (error.message() == "This is an error") 141 | }); 142 | ``` 143 | 144 | **3. Errors** 145 | 146 | A promise has an error if: 147 | - it is chained with a promise which has an error 148 | - an exception has been thrown with a PromiseError inside the lambda parameter of 'then()' 149 | - it has been explicitly rejected inside 'makePromise()' or using a 'Deferred' 150 | - the context object has been destroyed before starting the promise operation 151 | 152 | Within a promise chain, errors are propagated to the next 'fail()'s and the 'finally' lambda 153 | will be eventually called. 154 | 155 | An error consists of the following information: 156 | - message (QString) 157 | - id (int, optional) 158 | - data (QVariant, optional) 159 | - isContextDestroyed (bool, automatically set when the error results from context destruction) 160 | 161 | **4. Promise context** 162 | 163 | A context may be defined for a promise chain by starting a chain with a 'PromiseContext' instance. 164 | 165 | A promise context is especially useful: 166 | - to restrict the lifetime of the promise to the one of a QObject instance (e.g. 'this') 167 | - as a container for the variables used within a promise chain 168 | - to define which thread/event loop is used for the promise chain 169 | 170 | *Context scope* 171 | 172 | The context is applied to all chained promises created within the scope of the PromiseContext instance. 173 | This means that the promises which have been chained after the PromiseContext instance has been 174 | deleted will not use that context. 175 | 176 | Example: 177 | ```c++ 178 | auto promise = PromiseContext(ctx).then(...).then(...); // context applied 179 | promise.then(...); // context not applied 180 | ``` 181 | 182 | Not recommended (but valid code): 183 | ```c++ 184 | Promise promise; 185 | { 186 | auto context = PromiseContext(ctx); 187 | promise = promise.then(...); // context not applied 188 | promise = context.then(...); // context applied 189 | promise = promise.then(...); // context applied, too 190 | } 191 | promise.then(...); // context not applied 192 | ``` 193 | 194 | *QObject as promise context* 195 | 196 | When giving a QObject as context, we can: 197 | - limit the lifetime of the promise chain: the promise chain is interrupted when ctx has been destroyed 198 | - use the context as container for the variables used inside the promise chain 199 | - use the context as parent of QObject instances created and used inside the promise chain 200 | - trigger lambdas in the event loop of the context object thread 201 | 202 | Note: on destruction of the context, the next promises operations ('then()') are skipped and the 'fail()' and 203 | 'finally()' lambdas are called. 204 | 205 | Example: 206 | ```c++ 207 | struct ContextObject : QObject { 208 | int contextVariable = -1; 209 | }; 210 | auto ctx = new ContextObject(); 211 | 212 | auto promise = PromiseContext(ctx) 213 | .then([=]() { 214 | ctx->contextVariable = 1; 215 | }) 216 | .then([]() { 217 | // Skipped if the context object has been destroyed 218 | }) 219 | .fail([](const PromiseError &error) { 220 | if (error.isContextDestroyed()) { 221 | // when the error has been caused by the destruction of the context object 222 | } 223 | }) 224 | .finally([](QObject *ctx) { 225 | // Note: ctx == nullptr if the context object has been destroyed 226 | }); 227 | 228 | promise.then([]() { 229 | // No context anymore (even if the context object still exists) 230 | }); 231 | ``` 232 | 233 | *QThread as promise context* 234 | 235 | Alternatively, you can give a QThread or a QThreadPool to explicitly trigger the promise execution 236 | (each step of the promise) in the event loop of a specific thread. 237 | 238 | Example: 239 | ```c++ 240 | QThread *thread = new QThread(); 241 | thread->start(); // start thread's event loop 242 | 243 | auto promise = PromiseContext(thread) 244 | .then([]() { 245 | // Running in the thread 246 | }); 247 | ``` 248 | 249 | **3. Defers** 250 | 251 | Defers can be either implicitely created using 'makePromise()' or with an explicit 'Deferred' instance. 252 | 253 | Using makePromise() (c++14 only!): 254 | ```c++ 255 | auto promise = makePromise([](auto resolve, auto reject) { 256 | if (ok) { 257 | resolve(10); 258 | } else { 259 | reject(PromiseError(...)); 260 | } 261 | }); 262 | ``` 263 | 264 | Using Deferred: 265 | ```c++ 266 | Deferred defer; 267 | auto promise = defer.promise(); 268 | 269 | if (ok) { 270 | defer.resolve(10); 271 | } else { 272 | defer.reject(PromiseError(...)); 273 | } 274 | ``` 275 | 276 | **4. Connect object signals** 277 | 278 | *Using makeConnectionPromise* 279 | 280 | You can create a Promise which is automatically resolved as soon as the signal of a given object has been 281 | emitted. 282 | 283 | Note1: the type of the promise depends on the first parameter of the signal. 284 | 285 | Example: 286 | ```c++ 287 | auto timer = new QTimer(); 288 | timer->start(3000); 289 | makeConnectionPromise(timer, &QTimer::timeout) 290 | .then([=]() { 291 | // 3 seconds later... 292 | delete timer; 293 | return makeConnectionPromise(emitter, &MyClass::intSignal); 294 | }) 295 | .then([=](int value) { 296 | // Reached when intSignal has been emitted for the emitter instance with 'value' as parameter 297 | }); 298 | ``` 299 | 300 | *Using Deferred* 301 | 302 | For more complex operations, a Deferred can be used. This can be done do define custom actions 303 | after signal emittion and to trigger error. 304 | 305 | Example: 306 | ```c++ 307 | auto downloadManager = new DownloadManager(); 308 | downloadManager->download("https://www.url.com/file"); 309 | 310 | Deferred defer; 311 | 312 | defer.connect(emitter, &MyClass::progress, [](double progress) { 313 | qDebug() << "Progress:" << (int)(progress * 100.0) << "%"; 314 | }); 315 | defer.connectAndResolve(emitter, &MyClass::downloadSuccessful); 316 | defer.connectAndReject(emitter, &MyClass::downloadError, PromiseError("Download error")); 317 | 318 | defer.promise() 319 | .then([](const QByteArray &data) { 320 | qDebug() << "Successfully downloaded" << data.count() << "bytes!"; 321 | }) 322 | .fail([](const PromiseError &error) { 323 | qDebug() << "Failed:" << error.message(); 324 | }) 325 | .finally([=]() { 326 | delete downloadedManager; 327 | }); 328 | ``` 329 | 330 | 331 | **5. Integration with QtConcurrent/QFuture** 332 | 333 | A promise can be defined based on a QFuture, which makes it easy to keep compatible with 334 | QtConcurrent. 335 | 336 | Example: 337 | ```c++ 338 | Promise() 339 | .then([]() { 340 | auto future = QtConcurrent::run([]() { 341 | // Code running in a thread of the current thread pool 342 | return 12; 343 | }); 344 | return future; 345 | .then([](int value) { 346 | // value == 12 347 | }); 348 | ``` 349 | 350 | **6. Concurrent/combined promises** 351 | 352 | TODO 353 | 354 | 355 | Example 356 | ======== 357 | 358 | ```c++ 359 | using namespace QtPromise; 360 | 361 | // Context object with data used inside the promise chain and whose lifetime 362 | // depends on 'this' instance 363 | struct ContextObject : QObject { 364 | QNetworkReply *reply = nullptr; 365 | qint64 bytesReceived = -1LL; 366 | }; 367 | auto ctx = new ContextObject(); 368 | ctx->setParent(this); 369 | 370 | Promise downloadPromise = PromiseContext(ctx) 371 | .then([]() { 372 | qDebug() << "Promise chain started!"; 373 | }) 374 | .delay(1000) 375 | .then([ctx]() { 376 | // Like above but with an explicit timer 377 | auto timer = new QTimer(ctx); 378 | timer->start(1000); 379 | return makeConnectionPromise(timer, &QTimer::timeout); 380 | }) 381 | .then(selectUrlPromise()) 382 | .then([ctx](const QUrl &url) { 383 | if (!url.isValid()) { 384 | throw PromiseError("No URL has been selected"); 385 | } 386 | 387 | qDebug() << "Downloading" << url.toString() << "..."; 388 | 389 | QNetworkRequest request(url); 390 | auto nam = new QNetworkAccessManager(ctx); 391 | ctx->reply = nam->get(request); 392 | 393 | Deferred defer; 394 | defer.connect(ctx->reply, &QNetworkReply::downloadProgress, [ctx](qint64 bytesReceived, qint64 bytesTotal) { 395 | if (bytesReceived != ctx->bytesReceived) { 396 | double progress = double(bytesReceived) / double(bytesTotal); 397 | qDebug() << "Download progress:" << int(progress * 100.0) << "%"; 398 | ctx->bytesReceived = bytesReceived; 399 | } 400 | }); 401 | defer.connectAndResolve(ctx->reply, &QNetworkReply::finished); 402 | return defer.promise(); 403 | }) 404 | .then([ctx]() { 405 | ctx->reply->deleteLater(); 406 | 407 | if (ctx->reply->error() != QNetworkReply::NoError) { 408 | qDebug() << "Download failed :("; 409 | throw PromiseError(ctx->reply->errorString()); 410 | } 411 | 412 | qDebug() << "Download successful :)"; 413 | return ctx->reply->readAll(); 414 | }) 415 | .fail([](const PromiseError &error) { 416 | // Called if any of the previous promise in the chain has failed 417 | qWarning() << "Error:" << error.message(); 418 | }) 419 | .finally([](QObject *ctx) { 420 | // Called on completion (when successfull or after first fail) 421 | if (!ctx) { 422 | qWarning() << "Context has been destroyed during promise chain execution"; 423 | } 424 | 425 | // Clean-up data 426 | delete ctx; 427 | }); 428 | 429 | // Chain previous promise 430 | downloadPromise 431 | .then([](const QByteArray &data) { 432 | auto processData = [](const QByteArray &data) { 433 | // CPU-intensive operation performed in a separate thread 434 | int sum = 0; 435 | for (const QChar &c : data) { 436 | sum += c.toLatin1(); 437 | } 438 | 439 | return sum; 440 | }; 441 | 442 | // Return a QFuture 443 | return QtConcurrent::run(processData, data); 444 | }) 445 | .then([](int sum) { 446 | qDebug() << "Calculated sum:" << sum; 447 | }) 448 | .fail([]() { 449 | qDebug() << "Could not calculate sum :("; 450 | }); 451 | .finally([]() { 452 | qDebug() << "Done!"; 453 | }); 454 | ``` 455 | 456 | 457 | Installation 458 | ======== 459 | 460 | QtPromise consists of a single header file (promise.h). Just include it in your project and enjoy :) 461 | 462 | 463 | API 464 | ======== 465 | 466 | QtPromise is implemented inside a `QtPromise` namespace. 467 | 468 | Promise 469 | --------------- 470 | 471 | ```c++ 472 | template 473 | class Promise 474 | ``` 475 | 476 | **Promise() (if T = void)** 477 | **Promise(T value) (if T != void)** 478 | 479 | Create a fulfilled promise with a value. 480 | 481 | **Promise then(Functor func)** 482 | 483 | Chain the current promise and return a new promise. The function is sent to the 484 | queue of the current event loop (or the one corresponding to the current promise 485 | context) as soon as the current promise has been resolved. If the current promise 486 | has failed or has been cancelled, func() will not be called. 487 | 488 | The new promise depends on the return value of func: 489 | - Promise: returns a Promise which matches the state and the 490 | value of the other promise 491 | - QFuture: returns a Promise which will be resolved as soon as 492 | the future is completed (or cancelled when the future has been cancelled) 493 | - Any other value of type ValueType: returns a fulfilled promise with the same value 494 | 495 | When a PromiseError() exception is thrown with the execution of func, 'then()' returns 496 | a failed promise with the corresponding error. 497 | 498 | **Promise then(const Promise &otherPromise) const** 499 | 500 | Chain a promise with another promise: returns a new promise which matches the state and the 501 | value of the given promise. 502 | 503 | **Promise delay(int ms) const** 504 | **Promise delay(std::chrono) const** 505 | 506 | TODO 507 | 508 | **Promise fail() const** 509 | **Promise fail(const PromiseError &error)const** 510 | 511 | Executed if the promise has failed due to a previous error during the execution of the 512 | promise chain. 513 | 514 | Note: the 'fail()' call does not change the state and the value of the returned promise. 515 | The promise still has an error and the subsequent 'then()' operations will be skipped. It is 516 | possible, however, to recover from an error by returning a new promise (e.g. 517 | 'Promise(12)' or to change the error by throwing another PromiseError() inside the 518 | 'fail()' lambda. 519 | 520 | **Promise finally() const** 521 | **Promise finally(const QObject *ctx) const** 522 | 523 | Executed after the current promise has been completed (successfully or after an error). 524 | 525 | Note: the 'finally()' call does not change the state and the value of a promise. 526 | 527 | **T value() const (if T != void)** 528 | 529 | Note: returns the value of a fulfilled promise. If the promise is still pending or has 530 | an error, a default constructed value is returned ('T()'). 531 | 532 | **PromiseError error() const** 533 | 534 | Note: returns the error of a failing promise. If the promise is still pending or does not 535 | have an error, a default 'PromiseError()' is returned. 536 | 537 | **bool isPending() const** 538 | 539 | **bool isFinished() const** 540 | 541 | **bool isFulfilled() const** 542 | 543 | **bool hasError() const** 544 | 545 | **bool isCanceled() const** 546 | 547 | **Promise makePromise(MakePromiseFunc func)** 548 | 549 | Helper function to create a Promise by providing the resolve() and reject() functions. 550 | 551 | 'func' should be a function with the following signature: 552 | ```c++ 553 | func(ResolveFunc resolve, RejectFunc reject) -> void 554 | ``` 555 | 556 | The code inside the given function is immediately executed. The resulting promise 557 | is pending until resolve() or reject() has been called. 558 | 559 | Example: 560 | ```c++ 561 | makePromise([](auto resolve, auto reject) { 562 | QTimer::singleShot(10, [=]() { 563 | int randomValue = qrand(); 564 | if (randomValue % 2) { 565 | resolve(randomValue); 566 | } else { 567 | reject(PromiseError("bad luck")); 568 | } 569 | }); 570 | }); 571 | ``` 572 | 573 | ConnectionPromise 574 | --------------- 575 | 576 | ```c++ 577 | template 578 | class ConnectionPromise : public Promise 579 | ``` 580 | 581 | **ConnectionPromise(QObject *emitter, PointerToObjectMethod signal)** 582 | 583 | TODO: 584 | Create a 'Promise' which will be resolved as soon as the given signal has been emitted. The promise 585 | value is the one of the first parameter of the emitted signal (or 'void' if the signal does not 586 | have any parameter). 587 | 588 | **makeConnectionPromise(QObject *emitter, PointerToObjectMethod signal)** 589 | 590 | Helper function to create a ConnectionPromise which is automatically resolved as soon as the signal 591 | of a given object has been emitted. 592 | 593 | ```c++ 594 | template 595 | ConnectionPromise makeConnectionPromise(QObject *emitter, PointerToObjectMethod signal) 596 | ``` 597 | 598 | PromiseError 599 | --------------- 600 | 601 | ```c++ 602 | class PromiseError 603 | ``` 604 | 605 | **PromiseError(const QString &msg, int id = -1)** 606 | 607 | **PromiseError(const QVariant &data, const QString &msg, int id = -1)** 608 | 609 | **bool isContextDestroyed() const** 610 | 611 | Deferred 612 | --------------- 613 | 614 | ```c++ 615 | template 616 | class Defer 617 | ``` 618 | 619 | **Deferred()** 620 | 621 | **Promise promise() const** 622 | 623 | **void resolve() (if T = void)** 624 | **void resolve(T) (if T != void)** 625 | 626 | **void reject()** 627 | 628 | **void connect(QObject *emitter, PointerToObjectMethod signal, Functor func)** 629 | **void connectAndResolve(QObject *emitter, PointerToObjectMethod signal)** 630 | **void connectAndResolve(QObject *emitter, PointerToObjectMethod signal, const T &value)** 631 | **void connectAndReject(QObject *emitter, PointerToObjectMethod signal, const PromiseError &error = PromiseError())** 632 | 633 | The connections used by the defer are automatically closed after resolving (or rejecting) the promise. 634 | 635 | PromiseContext 636 | --------------- 637 | 638 | ```c++ 639 | class PromiseContext 640 | ``` 641 | 642 | **PromiseContext(QObject *context)** 643 | **PromiseContext(QSharedPointer *context)** 644 | **PromiseContext(QThread *thread)** 645 | **PromiseContext(QThread *threadPool)** 646 | 647 | Start a promise chain with a context which is applied to all chained promises created within the 648 | scope of the PromiseContext instance. The promises which have been chained after the PromiseContext 649 | instance has been deleted will not use that context anymore. 650 | 651 | Note: PromiseContext is only intented to be used as a temporary instance and it is not recommended to 652 | store it as a variable. 653 | 654 | **void then(...ARGS)** 655 | 656 | PromiseGroup 657 | --------------- 658 | 659 | TODO 660 | 661 | ```c++ 662 | template 663 | class PromiseGroup : public Promise 664 | ``` 665 | 666 | **PromiseGroup(QObject *context)** 667 | 668 | **PromiseGroup(QSharedPointer *context)** 669 | 670 | **PromiseGroup(QThread *thread)** 671 | 672 | **PromiseGroup(QThread *threadPool)** 673 | 674 | **TODO: add + function** 675 | 676 | **TODO: add + promise** 677 | 678 | PromiseGroupResults 679 | --------------- 680 | 681 | TODO 682 | 683 | **template 684 | ResultType at(int index) const** 685 | 686 | **int count() const** 687 | 688 | Tests 689 | ======== 690 | 691 | See `test` directory. 692 | 693 | 694 | Author 695 | ======== 696 | 697 | Benoit Walter 698 | 699 | Note: Source code partially based on Ben Lau's AsyncFuture (https://github.com/benlau/asyncfuture). 700 | 701 | 702 | License 703 | ======== 704 | 705 | Apache License Version 2.0 (http://www.apache.org/licenses/) 706 | 707 | -------------------------------------------------------------------------------- /docs/QtPromise-MunichMeetup-20170523.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bwalter/qt-promise/0d6e02f76517405d5544f1cd95c2f6cae3940932/docs/QtPromise-MunichMeetup-20170523.pdf -------------------------------------------------------------------------------- /example/example.pro: -------------------------------------------------------------------------------- 1 | TEMPLATE = app 2 | TARGET = promiseExample 3 | 4 | QT += core gui network concurrent 5 | 6 | CONFIG -= c++11 7 | CONFIG += c++14 8 | CONFIG += console 9 | CONFIG -= app_bundle 10 | 11 | SOURCES = \ 12 | main.cpp \ 13 | promiseexample.cpp 14 | 15 | HEADERS = \ 16 | ../promise.h \ 17 | promiseexample.h 18 | 19 | INCLUDEPATH += \ 20 | .. 21 | -------------------------------------------------------------------------------- /example/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "promiseexample.h" 4 | 5 | int main(int argc, char *argv[]) 6 | { 7 | QCoreApplication a(argc, argv); 8 | 9 | PromiseExample *example = new PromiseExample(); 10 | QMetaObject::invokeMethod(example, "init"); 11 | 12 | return a.exec(); 13 | } 14 | -------------------------------------------------------------------------------- /example/promiseexample.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | ** 3 | ** Copyright (C) 2017 Benoit Walter 4 | ** Contact: benoit.walter@meerun.com 5 | ** 6 | ** Licensed to the Apache Software Foundation (ASF) under one 7 | ** or more contributor license agreements. See the NOTICE file 8 | ** distributed with this work for additional information 9 | ** regarding copyright ownership. The ASF licenses this file 10 | ** to you under the Apache License, Version 2.0 (the 11 | ** "License"); you may not use this file except in compliance 12 | ** with the License. You may obtain a copy of the License at 13 | ** 14 | ** http://www.apache.org/licenses/LICENSE-2.0 15 | ** 16 | ** Unless required by applicable law or agreed to in writing, 17 | ** software distributed under the License is distributed on an 18 | ** "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 19 | ** KIND, either express or implied. See the License for the 20 | ** specific language governing permissions and limitations 21 | ** under the License. 22 | ****************************************************************************/ 23 | 24 | #include "promiseexample.h" 25 | #include "promise.h" 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include 32 | #include 33 | 34 | using namespace QtPromise; 35 | 36 | static Promise selectUrlPromise(); 37 | 38 | PromiseExample::PromiseExample(QObject *parent) 39 | : QObject(parent) 40 | { 41 | } 42 | 43 | PromiseExample::~PromiseExample() 44 | { 45 | } 46 | 47 | void PromiseExample::init() 48 | { 49 | // Context object with data used inside the promise chain and whose lifecycle 50 | // depends on 'this' instance 51 | struct ContextObject : QObject { 52 | QNetworkReply *reply = nullptr; 53 | qint64 bytesReceived = -1LL; 54 | }; 55 | auto ctx = new ContextObject(); 56 | ctx->setParent(this); 57 | 58 | Promise downloadPromise = PromiseContext(ctx) 59 | .then([]() { 60 | qDebug() << "Promise chain started!"; 61 | }) 62 | //.delay(1000) 63 | .then([ctx]() { 64 | // Like above but with an explicit timer 65 | auto timer = new QTimer(ctx); 66 | timer->start(1000); 67 | return makeConnectionPromise(timer, &QTimer::timeout); 68 | }) 69 | //.then(selectUrlPromise()) 70 | .then([]() { 71 | return selectUrlPromise(); 72 | }) 73 | .then([ctx](const QUrl &url) { 74 | if (!url.isValid()) { 75 | throw PromiseError("No URL has been selected"); 76 | } 77 | 78 | qDebug() << "Downloading" << url.toString() << "..."; 79 | 80 | QNetworkRequest request(url); 81 | auto nam = new QNetworkAccessManager(ctx); 82 | ctx->reply = nam->get(request); 83 | 84 | Deferred defer; 85 | defer.connect(ctx->reply, &QNetworkReply::downloadProgress, [ctx](qint64 bytesReceived, qint64 bytesTotal) { 86 | if (bytesReceived != ctx->bytesReceived) { 87 | double progress = double(bytesReceived) / double(bytesTotal); 88 | qDebug() << "Download progress:" << int(progress * 100.0) << "%"; 89 | ctx->bytesReceived = bytesReceived; 90 | } 91 | }); 92 | defer.connectAndResolve(ctx->reply, &QNetworkReply::finished); 93 | return defer.promise(); 94 | }) 95 | .then([ctx]() { 96 | ctx->reply->deleteLater(); 97 | 98 | if (ctx->reply->error() != QNetworkReply::NoError) { 99 | qDebug() << "Download failed."; 100 | throw PromiseError(ctx->reply->errorString()); 101 | } 102 | 103 | qDebug() << "Download successful!"; 104 | return ctx->reply->readAll(); 105 | }) 106 | .fail([](const PromiseError &error) { 107 | // Called if any of the previous promise in the chain has failed 108 | qWarning() << "Error:" << error.message(); 109 | }) 110 | .finally([](QObject *ctx) { 111 | // Called on completion (when successfull or after first fail) 112 | if (!ctx) { 113 | qWarning() << "Context has been destroyed during promise chain execution"; 114 | } 115 | 116 | // Clean-up data 117 | delete ctx; 118 | }); 119 | 120 | // Chain previous promise 121 | downloadPromise 122 | .then([](const QByteArray &data) { 123 | auto processData = [](const QByteArray &data) { 124 | // CPU-intensive operation performed in a separate thread 125 | int sum = 0; 126 | for (const QChar &c : data) { 127 | sum += c.toLatin1(); 128 | } 129 | 130 | return sum; 131 | }; 132 | 133 | // Return a QFuture 134 | return QtConcurrent::run(processData, data); 135 | }) 136 | .then([](int sum) { 137 | qDebug() << "Calculated sum:" << sum; 138 | }) 139 | .fail([]() { 140 | qDebug() << "Could not calculate sum :("; 141 | }) 142 | .finally([]() { 143 | qApp->exit(); 144 | }); 145 | } 146 | 147 | Promise selectUrlPromise() { 148 | return Promise(QUrl("http://www.meerun.com")); 149 | } 150 | -------------------------------------------------------------------------------- /example/promiseexample.h: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | ** 3 | ** Copyright (C) 2017 Benoit Walter 4 | ** Contact: benoit.walter@meerun.com 5 | ** 6 | ** Licensed to the Apache Software Foundation (ASF) under one 7 | ** or more contributor license agreements. See the NOTICE file 8 | ** distributed with this work for additional information 9 | ** regarding copyright ownership. The ASF licenses this file 10 | ** to you under the Apache License, Version 2.0 (the 11 | ** "License"); you may not use this file except in compliance 12 | ** with the License. You may obtain a copy of the License at 13 | ** 14 | ** http://www.apache.org/licenses/LICENSE-2.0 15 | ** 16 | ** Unless required by applicable law or agreed to in writing, 17 | ** software distributed under the License is distributed on an 18 | ** "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 19 | ** KIND, either express or implied. See the License for the 20 | ** specific language governing permissions and limitations 21 | ** under the License. 22 | ****************************************************************************/ 23 | 24 | #pragma once 25 | 26 | #include 27 | 28 | class PromiseExample : public QObject 29 | { 30 | Q_OBJECT 31 | 32 | public: 33 | explicit PromiseExample(QObject *parent = nullptr); 34 | ~PromiseExample() override; 35 | 36 | public slots: 37 | void init(); 38 | }; 39 | 40 | -------------------------------------------------------------------------------- /promise.h: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | ** 3 | ** Copyright (C) 2017 Benoit Walter 4 | ** Contact: benoit.walter@meerun.com 5 | ** 6 | ** Contains code from AsyncFuture (https://github.com/benlau/asyncfuture) 7 | ** Copyright (C) 2017 Ben Lau 8 | ** 9 | ** Licensed to the Apache Software Foundation (ASF) under one 10 | ** or more contributor license agreements. See the NOTICE file 11 | ** distributed with this work for additional information 12 | ** regarding copyright ownership. The ASF licenses this file 13 | ** to you under the Apache License, Version 2.0 (the 14 | ** "License"); you may not use this file except in compliance 15 | ** with the License. You may obtain a copy of the License at 16 | ** 17 | ** http://www.apache.org/licenses/LICENSE-2.0 18 | ** 19 | ** Unless required by applicable law or agreed to in writing, 20 | ** software distributed under the License is distributed on an 21 | ** "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 22 | ** KIND, either express or implied. See the License for the 23 | ** specific language governing permissions and limitations 24 | ** under the License. 25 | ****************************************************************************/ 26 | 27 | // TODO: 28 | // static Promise::resolved(T) 29 | // PromiseContext(QThreadPool *) 30 | // Promise.delay(2000) 31 | // Promise.then(promise) 32 | // ConcurrentPromises(FailStrategy, QThreadPool *) << promise1 << promise2 << promise3 33 | 34 | #include 35 | #include 36 | #include 37 | #include 38 | #include 39 | #include 40 | #include 41 | #include 42 | #include 43 | 44 | namespace QtPromise { 45 | 46 | template 47 | class Promise; 48 | 49 | template 50 | class Deferred; 51 | 52 | class PromiseError { 53 | public: 54 | explicit PromiseError(const QString& msg = "") : m_msg(msg) {} 55 | 56 | PromiseError(const PromiseError &) = default; 57 | PromiseError& operator=(const PromiseError &) = default; 58 | 59 | bool isContextDestroyed() const { return m_contextDestroyed; } 60 | const QString& message() const { return m_msg; } 61 | 62 | // Internal 63 | void _setContextDestroyed() { m_contextDestroyed = true; } 64 | 65 | private: 66 | QString m_msg; 67 | bool m_contextDestroyed = false; 68 | }; 69 | 70 | namespace Private { 71 | 72 | template 73 | class Value { 74 | public: 75 | Value() {} 76 | Value(T &&v) : value(v) {} 77 | Value(const T &v) : value(v) {} 78 | Value(const T &&v) : value(v) {} 79 | Value(T *v) : value(*v) {} 80 | 81 | T value = T(); 82 | }; 83 | 84 | template <> 85 | class Value { 86 | public: 87 | Value() {} 88 | Value(void *) {} 89 | }; 90 | 91 | // Based on comment in: 92 | // http://stackoverflow.com/questions/21646467/how-to-execute-a-functor-or-a-lambda-in-a-given-thread-in-qt-gcd-style 93 | template 94 | static void runInObjectThread(QObject *object, F &&func) { 95 | using Func = typename std::decay::type; 96 | 97 | struct Event : public QEvent { 98 | Event(Func &&f) : QEvent(QEvent::None), func(std::move(f)) {} 99 | Event(const Func &f) : QEvent(QEvent::None), func(f) {} 100 | ~Event() { func(); } 101 | 102 | Func func; 103 | }; 104 | 105 | QCoreApplication::postEvent(object, new Event(std::forward(func))); 106 | } 107 | 108 | struct ConnectionReceiverWrapper { 109 | public: 110 | ConnectionReceiverWrapper() = delete; 111 | 112 | ConnectionReceiverWrapper(QObject *o, bool autoDelete) 113 | : m_receiverPtr(o) 114 | , m_autoDelete(autoDelete) { 115 | } 116 | 117 | ~ConnectionReceiverWrapper() { 118 | if (m_autoDelete && !m_receiverPtr.isNull()) { 119 | m_receiverPtr->deleteLater(); 120 | } 121 | } 122 | 123 | QObject *receiver() const { 124 | return m_receiverPtr.data(); 125 | } 126 | 127 | private: 128 | friend class SharedContext; 129 | 130 | QPointer m_receiverPtr; 131 | bool m_autoDelete; 132 | }; 133 | 134 | typedef QSharedPointer ConnectionReceiverWrapperPtr; 135 | 136 | typedef enum { Idle = 0, Running, Resolved, Rejected, Canceled, ContextDestroyed } DeferObjectStatus; 137 | 138 | template 139 | class DeferObject { 140 | public: 141 | typedef QSharedPointer> Ptr; 142 | 143 | ~DeferObject() { 144 | QObject::disconnect(m_contextDestroyedConnection); 145 | } 146 | 147 | // Create instance 148 | template 149 | static DeferObject::Ptr create(ARGS &&...args) { 150 | auto newInstance = new DeferObject(std::forward(args)...); 151 | auto ptr = Ptr(newInstance); 152 | newInstance->m_thisWeakPtr = ptr; 153 | return ptr; 154 | } 155 | 156 | void addCallback(const Private::ConnectionReceiverWrapperPtr &receiverWrapperPtr, std::function &&func) { 157 | { 158 | QWriteLocker lock(&m_lock); 159 | 160 | Q_ASSERT(!receiverWrapperPtr.isNull()); 161 | m_callbacks.append(qMakePair(receiverWrapperPtr, std::move(func))); 162 | } 163 | 164 | QReadLocker lock(&m_lock); 165 | 166 | if (m_status >= Resolved) { 167 | // Already completed 168 | _notify(); 169 | } 170 | } 171 | 172 | DeferObjectStatus status() const { 173 | QReadLocker lock(&m_lock); 174 | return m_status; 175 | } 176 | 177 | const Value &value() const { 178 | QReadLocker lock(&m_lock); 179 | return m_value; 180 | } 181 | 182 | const PromiseError &promiseError() const { 183 | QReadLocker lock(&m_lock); 184 | return m_promiseError; 185 | } 186 | 187 | void start() { 188 | QWriteLocker lock(&m_lock); 189 | 190 | Q_ASSERT(m_status == Idle); 191 | m_status = Running; 192 | 193 | // Do not listen any more for the context destroyed event 194 | QObject::disconnect(m_contextDestroyedConnection); 195 | } 196 | 197 | // Resolve without value 198 | void resolve() { 199 | { 200 | QWriteLocker lock(&m_lock); 201 | m_status = Resolved; 202 | } 203 | 204 | _notify(); 205 | } 206 | 207 | void resolve(Value value) { 208 | Q_UNUSED(value); 209 | 210 | { 211 | QWriteLocker lock(&m_lock); 212 | m_status = Resolved; 213 | } 214 | 215 | _notify(); 216 | } 217 | 218 | // Resolve with a non-void value 219 | template ::value>::type> 221 | void resolve(const U &value) { 222 | { 223 | QWriteLocker lock(&m_lock); 224 | 225 | m_status = Resolved; 226 | m_value = Value(value); 227 | } 228 | 229 | _notify(); 230 | } 231 | 232 | template ::value>::type> 234 | void resolve(const Value &value) { 235 | resolve(value.value); 236 | } 237 | 238 | // Resolve with a void promise 239 | template ::value>::type> 240 | void resolve(const Promise &promise); 241 | 242 | // Resolve with a non-void promise 243 | template ::value>::type> 244 | void resolve(const Promise &promise); 245 | 246 | // Resolve with a future 247 | void resolve(const QFuture &future) { 248 | if (future.isCanceled()) { 249 | cancel(); 250 | return; 251 | } 252 | 253 | if (future.isFinished()) { 254 | resolve(future.result()); 255 | return; 256 | } 257 | 258 | auto deleter = [](QFutureWatcher *instance) { 259 | instance->deleteLater(); 260 | }; 261 | auto newFutureWatcher = new QFutureWatcher(); 262 | newFutureWatcher->setFuture(future); 263 | QSharedPointer> watcher(newFutureWatcher, deleter); 264 | 265 | auto strongThis = m_thisWeakPtr.toStrongRef(); 266 | Q_ASSERT(!strongThis.isNull()); 267 | auto conn1 = QObject::connect(watcher.data(), &QFutureWatcher::finished, [strongThis, watcher]() { 268 | if (watcher->isCanceled()) { 269 | strongThis->cancel(); 270 | } else { 271 | strongThis->resolve(watcher->result()); 272 | } 273 | }); 274 | QObject::connect(watcher.data(), &QFutureWatcher::finished, [strongThis, conn1]() { 275 | QObject::disconnect(conn1); 276 | }); 277 | 278 | watcher->setFuture(future); 279 | } 280 | 281 | void reject(const PromiseError &promiseError) { 282 | { 283 | QWriteLocker lock(&m_lock); 284 | 285 | m_status = Rejected; 286 | m_promiseError = promiseError; 287 | } 288 | 289 | _notify(); 290 | } 291 | 292 | void cancel() { 293 | { 294 | QWriteLocker lock(&m_lock); 295 | m_status = Canceled; 296 | } 297 | 298 | _notify(); 299 | } 300 | 301 | private: 302 | template 303 | friend class DeferObject; // every Deferred is a friend 304 | 305 | DeferObject() = delete; 306 | 307 | explicit DeferObject(QObject *owner) 308 | : m_lock(QReadWriteLock::Recursive) { 309 | if (owner) { 310 | // Detect deletion of the context object 311 | m_contextDestroyedConnection = QObject::connect(owner, &QObject::destroyed, [=] { 312 | QWriteLocker lock(&m_lock); 313 | if (m_status == Idle) { 314 | m_status = ContextDestroyed; 315 | m_promiseError._setContextDestroyed(); 316 | 317 | lock.unlock(); 318 | _notify(); 319 | } 320 | }); 321 | } 322 | } 323 | 324 | void _notify() { 325 | QReadLocker lock(&m_lock); 326 | 327 | if (m_callbacks.isEmpty()) { 328 | return; 329 | } 330 | 331 | for (auto callback : qAsConst(m_callbacks)) { 332 | const ConnectionReceiverWrapperPtr &receiverWrapperPtr = callback.first; 333 | const std::function &func = callback.second; 334 | Q_ASSERT(!receiverWrapperPtr.isNull()); 335 | Q_ASSERT(receiverWrapperPtr->receiver()); 336 | if (receiverWrapperPtr->receiver()) { 337 | Q_ASSERT(func); 338 | auto thisWeakPtr = m_thisWeakPtr; 339 | auto safeFunc = [thisWeakPtr, func]() { 340 | auto thisStrong = thisWeakPtr.toStrongRef(); 341 | if (!thisStrong.isNull()) { 342 | QReadLocker lock(&thisStrong->m_lock); 343 | func(); 344 | } 345 | }; 346 | runInObjectThread(receiverWrapperPtr->receiver(), safeFunc); 347 | } 348 | } 349 | 350 | m_callbacks.clear(); 351 | } 352 | 353 | QWeakPointer> m_thisWeakPtr; 354 | mutable QReadWriteLock m_lock; 355 | 356 | DeferObjectStatus m_status = Idle; 357 | Value m_value; 358 | PromiseError m_promiseError; // TODO: optional? 359 | QMetaObject::Connection m_contextDestroyedConnection; 360 | QList>> m_callbacks; 361 | }; 362 | 363 | // Determine the input type a QFuture 364 | template 365 | struct future_traits { 366 | enum { 367 | is_future = 0 368 | }; 369 | 370 | typedef void arg_type; 371 | }; 372 | 373 | template