From eac5c93e5bc5231d95630655ae4c3dca0313c5d0 Mon Sep 17 00:00:00 2001 From: Qize Huang Date: Tue, 29 May 2018 09:08:36 +0800 Subject: [PATCH] add qAwait() function --- examples/using_iodevice/main.cpp | 26 ++++++++++++++++++++++ examples/using_iodevice/using_iodevice.pro | 10 +++++++++ include/coroutine_utils.h | 14 ++++++++---- 3 files changed, 46 insertions(+), 4 deletions(-) create mode 100644 examples/using_iodevice/main.cpp create mode 100644 examples/using_iodevice/using_iodevice.pro diff --git a/examples/using_iodevice/main.cpp b/examples/using_iodevice/main.cpp new file mode 100644 index 00000000..02d2f726 --- /dev/null +++ b/examples/using_iodevice/main.cpp @@ -0,0 +1,26 @@ +#include +#include +#include +#include +#include +#include "../../qtnetworkng.h" + +using namespace qtng; + +int main(int argc, char **argv) +{ + QApplication app(argc, argv); + QSharedPointer text(new QPlainTextEdit); + text->show(); + CoroutineGroup operations; + operations.spawn([text] { + QNetworkAccessManager manager; + QUrl url("http://download.qt.io/online/qt5/linux/x64/online_repository/Updates.xml"); + QNetworkRequest request(url); + QNetworkReply *reply = manager.get(request); + qAwait(reply, &QNetworkReply::finished); + text->setPlainText(reply->readAll()); + reply->deleteLater(); + }); + return startQtLoop(); +} diff --git a/examples/using_iodevice/using_iodevice.pro b/examples/using_iodevice/using_iodevice.pro new file mode 100644 index 00000000..c2658f86 --- /dev/null +++ b/examples/using_iodevice/using_iodevice.pro @@ -0,0 +1,10 @@ +###################################################################### +# Automatically generated by qmake (3.1) Tue May 29 08:36:34 2018 +###################################################################### + +TEMPLATE = app +QT+= widgets network +TARGET = using_iodevice +DEFINES += QT_DEPRECATED_WARNINGS +SOURCES += main.cpp +include(../../qtnetworkng.pri) diff --git a/include/coroutine_utils.h b/include/coroutine_utils.h index 5d9c812f..a34b6861 100755 --- a/include/coroutine_utils.h +++ b/include/coroutine_utils.h @@ -84,14 +84,20 @@ void runLocalLoop(EventLoop *loop) } -template -void waitSignal(const QObject *obj, Func1 signal, const QObject *context, Qt::ConnectionType type = Qt::DirectConnection) +template +void qAwait(const typename QtPrivate::FunctionPointer::Object *obj, Func signal) { QSharedPointer event(new Event); - QObject::connect(obj, signal, [event] { + const auto connection = QObject::connect(obj, signal, [event] { event->set(); }); - event->wait(); + try { + event->wait(); + QObject::disconnect(connection); + } catch (...) { + QObject::disconnect(connection); + throw; + } }