callback test

This commit is contained in:
王劲鹏 2019-12-19 20:24:44 +08:00
parent 3b287974ab
commit 7443e5c1c9
4 changed files with 47 additions and 6 deletions

View File

@ -11,7 +11,7 @@ class AsyncResult {
private: private:
QVariant result; QVariant result;
Callback<R> *callback; Callback<R> *callback = nullptr;
public: public:
AsyncResult() {} AsyncResult() {}
@ -28,7 +28,7 @@ public:
} }
} }
void setError(QException *exception) { void setError(QException exception) {
this->result->setValue(exception); this->result->setValue(exception);
if (callback != nullptr) { if (callback != nullptr) {
this->callback->onError(exception); this->callback->onError(exception);
@ -44,6 +44,17 @@ public:
R *getResult() { R *getResult() {
return static_cast<R*>(result.data()); return static_cast<R*>(result.data());
} }
void setCallback(Callback<R> *callback) {
this->callback = callback;
if (QException *exception = static_cast<QException*>(result.data())) {
this->callback->onError(*exception);
this->callback->onFinish();
} else if (hasResult()) {
this->callback->onResult(*getResult());
this->callback->onFinish();
}
}
}; };
#endif // ASYNC_RESULT_H #endif // ASYNC_RESULT_H

View File

@ -58,5 +58,6 @@ HEADERS += \
plugin/shader_plugin.h \ plugin/shader_plugin.h \
registry.h \ registry.h \
shader/layer.h \ shader/layer.h \
template/custom_callback.h \
template/singleton.h \ template/singleton.h \
utility/utility.h utility/utility.h

View File

@ -5,6 +5,7 @@
#include "context_manager.h" #include "context_manager.h"
#include "async/async_result.h" #include "async/async_result.h"
#include "template/custom_callback.h"
int main(int argc, char *argv[]) int main(int argc, char *argv[])
{ {
@ -31,10 +32,15 @@ int main(int argc, char *argv[])
delete source; delete source;
} }
{
// code for test
QJsonValue *a = new QJsonValue(); QJsonValue *a = new QJsonValue();
AsyncResult<QJsonValue> *result = new AsyncResult<QJsonValue>(*a); AsyncResult<QJsonValue> *result = new AsyncResult<QJsonValue>(*a);
CustomCallback<QJsonValue> *callback = new CustomCallback<QJsonValue>();
result->setCallback(callback);
qDebug() << result->hasResult(); qDebug() << result->hasResult();
qDebug() << result->getResult(); qDebug() << result->getResult();
}
return app.exec(); return app.exec();
} }

View File

@ -0,0 +1,23 @@
#ifndef CUSTOM_CALLBACK_H
#define CUSTOM_CALLBACK_H
#include "async/callback.h"
template <class R>
class CustomCallback : public Callback<R> {
public:
void onResult(R result) override {
}
void onError(QException exception) override {
}
void onFinish() override {
}
};
#endif // CUSTOM_CALLBACK_H