feat: add a finally callback to NetworkRequests (#2350)

Co-authored-by: Rasmus Karlsson <rasmus.karlsson@pajlada.com>
This commit is contained in:
Leon Richardt
2021-01-16 18:25:56 +01:00
committed by GitHub
parent f19cc60a5b
commit 0542b81a03
6 changed files with 186 additions and 1 deletions
+52 -1
View File
@@ -132,6 +132,7 @@ void loadUncached(const std::shared_ptr<NetworkData> &data)
data->timer_, &QTimer::timeout, worker, [reply, data]() {
qCDebug(chatterinoCommon) << "Aborted!";
reply->abort();
if (data->onError_)
{
postToThread([data] {
@@ -139,6 +140,13 @@ void loadUncached(const std::shared_ptr<NetworkData> &data)
{}, NetworkResult::timedoutStatus));
});
}
if (data->finally_)
{
postToThread([data] {
data->finally_();
});
}
});
}
@@ -159,17 +167,26 @@ void loadUncached(const std::shared_ptr<NetworkData> &data)
if (reply->error() ==
QNetworkReply::NetworkError::OperationCanceledError)
{
//operation cancelled, most likely timed out
// Operation cancelled, most likely timed out
return;
}
if (data->onError_)
{
auto status = reply->attribute(
QNetworkRequest::HttpStatusCodeAttribute);
// TODO: Should this always be run on the GUI thread?
postToThread([data, code = status.toInt()] {
data->onError_(NetworkResult({}, code));
});
}
if (data->finally_)
{
postToThread([data] {
data->finally_();
});
}
return;
}
@@ -196,6 +213,16 @@ void loadUncached(const std::shared_ptr<NetworkData> &data)
// log("finished {}", data->request_.url().toString());
reply->deleteLater();
if (data->finally_)
{
if (data->executeConcurrently_)
QtConcurrent::run([finally = std::move(data->finally_)] {
finally();
});
else
data->finally_();
}
};
if (data->timer_ != nullptr)
@@ -271,6 +298,30 @@ void loadCached(const std::shared_ptr<NetworkData> &data)
});
}
}
if (data->finally_)
{
if (data->executeConcurrently_ || isGuiThread())
{
if (data->hasCaller_ && !data->caller_.get())
{
return;
}
data->finally_();
}
else
{
postToThread([data]() {
if (data->hasCaller_ && !data->caller_.get())
{
return;
}
data->finally_();
});
}
}
}
}