Skip to content

QFuture

ModuleCore
Include
#include <QCoroFuture>
CMake
target_link_libraries(myapp QCoro::Core)
QMake
QT += QCoroCore

QFuture, which represents an asynchronously executed call, doesn't have any operation on its own that could be awaited asynchronously, this is usually done through a helper class called QFutureWatcher. To simplify the API, QCoro allows to directly co_await completion of the running QFuture or use a wrapper class QCoroFuture. To wrap a QFuture into a QCoroFuture, use qCoro():

template<typename T>
QCoroFuture qCoro(const QFuture<T> &future);

waitForFinished()

 Waits until the future is finished and then returns the result of the future (or nothing, if the future
 is a `QFuture<void>`.

 If the call is already finished or has an error, the coroutine will not suspend and the `co_await`
 expression will return immediatelly.

 This is a coroutine-friendly equivalent to using [`QFutureWatcher`][qdoc-qfuturewatcher]:

 ```cpp
 QFuture<QString> future = QtConcurrent::run([]() { ... });
 QFutureWatcher<QString> *watcher = new QFutureWatcher<QString>();
 QObject::connect(watcher, &QFutureWatcher<QString>::finished,
                  this, [watcher]() {
                      watcher->deleteLater();
                      const QStrign result = watcher->result();
                      ...
                  });
 ```

 You can also await completion of the future without using `QCoroFuture` at all by directly co-awaiting the
 `QFuture` object:

 ```cpp
 const QString result = co_await QtConcurrent::run([]() { ... });
 ```

Example

#include <QCoroFuture>

QCoro::Task<> runTask() {
    // Starts a concurrent task and co_awaits on the returned QFuture. While the task is
    // running, the coroutine is suspended.
    const QString value = co_await QtConcurrent::run([]() {
        QString result;
        ...
        // do some long-running computation
        ...
        return result;
    });
    // When the future has finished, the coroutine is resumed and the result of the
    // QFuture is returned and stored in `value`.

    // ... now do something with the value
}