File indexing completed on 2024-05-12 05:25:57

0001 /*
0002     Copyright (c) 2015 Christian Mollekopf <mollekopf@kolabsys.com>
0003 
0004     This library is free software; you can redistribute it and/or modify it
0005     under the terms of the GNU Library General Public License as published by
0006     the Free Software Foundation; either version 2 of the License, or (at your
0007     option) any later version.
0008 
0009     This library is distributed in the hope that it will be useful, but WITHOUT
0010     ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
0011     FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Library General Public
0012     License for more details.
0013 
0014     You should have received a copy of the GNU Library General Public License
0015     along with this library; see the file COPYING.LIB.  If not, write to the
0016     Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
0017     02110-1301, USA.
0018 */
0019 #pragma once
0020 
0021 #include <KAsync/Async>
0022 #include <QtConcurrent/QtConcurrentRun>
0023 #include <QFuture>
0024 #include <QFutureWatcher>
0025 
0026 namespace async {
0027 template <typename T>
0028 KAsync::Job<T> run(const std::function<T()> &f, bool runAsync = true)
0029 {
0030     if (runAsync) {
0031         return KAsync::start<T>([f](KAsync::Future<T> &future) {
0032             auto result = QtConcurrent::run(f);
0033             auto watcher = new QFutureWatcher<T>;
0034             QObject::connect(watcher, &QFutureWatcher<T>::finished, watcher, [&future, watcher]() {
0035                 future.setValue(watcher->future().result());
0036                 delete watcher;
0037                 future.setFinished();
0038             });
0039             watcher->setFuture(result);
0040         });
0041     } else {
0042         return KAsync::start<T>([f]() {
0043             return f();
0044         });
0045     }
0046 }
0047 }