This repository has been archived on 2024-07-22. You can view files and clone it, but cannot push or open issues or pull requests.
Doric/doric-Qt/doric/async/async_result.h

61 lines
1.3 KiB
C
Raw Normal View History

2019-12-19 19:54:58 +08:00
#ifndef ASYNC_RESULT_H
#define ASYNC_RESULT_H
#include <QDebug>
#include <QVariant>
#include "callback.h"
template <class R>
class AsyncResult {
private:
QVariant result;
2019-12-19 20:24:44 +08:00
Callback<R> *callback = nullptr;
2019-12-19 19:54:58 +08:00
public:
AsyncResult() {}
AsyncResult(R result) {
this->result.setValue(result);
}
void setResult(R result) {
this->result.setValue(result);
if (callback != nullptr) {
this->callback->onResult(result);
this->callback->onFinish();
}
}
2019-12-19 20:24:44 +08:00
void setError(QException exception) {
2019-12-19 19:54:58 +08:00
this->result->setValue(exception);
if (callback != nullptr) {
this->callback->onError(exception);
this->callback->onFinish();
}
}
bool hasResult() {
qDebug() << result.typeName();
return !QString(result.typeName()).isEmpty();
}
R *getResult() {
return static_cast<R*>(result.data());
}
2019-12-19 20:24:44 +08:00
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();
}
}
2019-12-19 19:54:58 +08:00
};
#endif // ASYNC_RESULT_H