1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
|
[](https://github.com/qcoro/qcoro/actions/workflows/build-linux.yml)
[](https://github.com/qcoro/qcoro/actions/workflows/build-windows.yml)
[](https://github.com/qcoro/qcoro/actions/workflows/build-macos.yml)
[](https://github.com/qcoro/qcoro/actions/workflows/update-docs.yml)
[](https://github.com/qcoro/qcoro/releases)



# QCoro - Coroutines for Qt5 and Qt6
The QCoro library provides set of tools to make use of C++20 coroutines with Qt.
Take a look at the example below to see what an amazing thing coroutines are:
```cpp
QNetworkAccessManager networkAccessManager;
// co_await the reply - the coroutine is suspended until the QNetworkReply is finished.
// While the coroutine is suspended, *the Qt event loop runs as usual*.
const QNetworkReply *reply = co_await networkAccessManager.get(url);
// Once the reply is finished, your code resumes here as if nothing amazing has just happened ;-)
const auto data = reply->readAll();
```
It requires a compiler with support for the couroutines TS, see [documentation](https://qcoro.dev/#supported-compilers) for a list of supported compilers and versions.
## Documentation
π π [Documentation](https://qcoro.dev/)
## Supported Qt Types
QCoro provides the tools necessary to make easy use of C++20 coroutines with Qt. The cornerstone of
the library is `QCoro::Task<T>`, which represents an executed coroutine and allows the result of
the coroutine to be asynchronously awaited by its caller. Additionally, QCoro provides a set of
wrappers for common Qt types, such as `QTimer`, `QNetworkReply`, `QDBusPendingCall`, `QFuture`
and others, that allow to `co_await` their asynchronous operations directly.
Additionally, there's a magical `qCoro()` function that can wrap many native Qt functions and types
to make them coroutine-friendly.
Go check the [documentation](https://qcoro.dev/reference/coro) for a full list of all supported
features and Qt types.
### `QDBusPendingCall`
QCoro can wait for an asynchronous D-Bus call to finish. There's no need to use `QDBusPendingCallWatcher`
with QCoro - just `co_await` the result instead. While co_awaiting, the Qt event loop runs as usual.
```cpp
QDBusInterface remoteServiceInterface{serviceName, objectPath, interface};
const QDBusReply<bool> isReady = co_await remoteServiceInterface.asyncCall(QStringLiteral("isReady"));
```
π [Full documentation here](https://qcoro.dev/reference/dbus/qdbuspendingcall).
### `QFuture`
QFuture represents a result of an asynchronous task. Normally you have to use `QFutureWatcher` to get
notified when the future is ready. With QCoro, you can just `co_await` it!
```cpp
const QFuture<int> task1 = QtConcurrent::run(....);
const QFuture<int> task2 = QtConcurrent::run(....);
const int a = co_await task1;
const int b = co_await task2;
co_return a + b;
```
π [Full documentation here](https://qcoro.dev/reference/core/qfuture).
### `QNetworkReply`
Doing network requests with Qt can be tedious - the signal/slot approach breaks the flow
of your code. Chaining requests and error handling quickly become mess and your code is
broken into numerous functions. But not with QCoro, where you can simply `co_await` the
`QNetworkReply` to finish:
```cpp
QNetworkAccessManager qnam;
QNetworkReply *reply = qnam.get(QStringLiteral("https://github.com/qcoro/qcoro"));
const auto contents = co_await reply;
reply->deleteLater();
if (reply->error() != QNetworkReply::NoError) {
co_return handleError(reply);
}
const auto link = findLinkInReturnedHtmlCode(contents);
reply = qnam.get(link);
const auto data = co_await reply;
reply->deleteLater();
if (reply->error() != QNetworkReply::NoError) {
co_return handleError(reply);
}
...
```
π [Full documentation here](https://qcoro.dev/reference/network/qnetworkreply).
### `QTimer`
Maybe you want to delay executing your code for a second, maybe you want to execute some
code in repeated interval. This becomes super-trivial with `co_await`:
```cpp
QTimer timer;
timer.setInterval(1s);
timer.start();
for (int i = 1; i <= 100; ++i) {
co_await timer;
qDebug() << "Waiting for " << i << " seconds...";
}
qDebug() << "Done!";
```
π [Full documentation here](https://qcoro.dev/reference/core/qtimer).
### `QIODevice`
`QIODevice` is a base-class for many classes in Qt that allow data to be asynchronously
written and read. How do you find out that there are data ready to be read? You could
connect to `QIODevice::readyRead()` singal, or you could use QCoro and `co_await` the object:
```cpp
socket->write("PING");
// Waiting for "pong"
const auto data = co_await socket;
co_return calculateLatency(data);
```
π [Full documentation here](https://qcoro.dev/reference/core/qiodevice).
### ...and more!
Go check the [full documentation](https://qcoro.dev) to learn more.
## .then() continuations
Sometimes it's not possible to use `co_await` to handle result of a coroutine - usually
when interfacing with a 3rd party code that does not support coroutines. In those
scenarios it's possible to chain a continuation callback to the coroutine which will
get invoked asynchronously when the coroutine finishes.
```cpp
void regularFunction() {
someCoroutineReturningInt().then([](int result) {
// handle result
});
}
```
The continuation callback can also be a coroutine and the result of the entire
expression is Task<T> where T is the return type of the continuation. Thanks to
that it's possible to `co_await` the entire chain, or chain multiple `.then()`
continuations.
π [Full documentation here](https://qcoro.dev/reference/coro/task).
## Generators
Generator is a coroutine that lazily produces multiple values. While there's
nothing Qt-specific, QCoro provides the necessary tools for users to create
custom generators in their Qt applications.
QCoro provides API for both synchronous generators (`QCoro::Generator<T>`)
and asynchronous generators (`QCoro::AsyncGenerator<T>`). Both generators provide
container-like API: `begin()` and `end()` member functions that return iterator-like
objects, which is well-known and established API and makes generators compatible
with existing algorithms.
```cpp
QCoro::Generator<quint64> fibonacci() {
quint64 a = 0, b = 1;
Q_FOREVER {
co_yield a;
a = std::exchange(b, a + b);
}
}
void printFib(quint64 max) {
for (auto fib : fibonacci()) {
if (fib > max) {
break;
}
std::cout << fib << std::endl;
}
}
```
π [Full documentation here](https://qcoro.dev/reference/coro/generator).
## License
```text
MIT License
Copyright (c) 2022 Daniel VrΓ‘til <dvratil@kde.org>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```
|