userver: userver/engine/task/task_with_result.hpp Source File
Loading...
Searching...
No Matches
task_with_result.hpp
Go to the documentation of this file.
1#pragma once
2
5
6#include <memory>
7#include <stdexcept>
8#include <utility>
9
11#include <userver/engine/impl/task_context_holder.hpp>
14#include <userver/utils/impl/wrapped_call.hpp>
15
16USERVER_NAMESPACE_BEGIN
17
18namespace engine {
19
31template <typename T>
32class [[nodiscard]] TaskWithResult : public Task {
33public:
37 TaskWithResult() = default;
38
39 TaskWithResult(const TaskWithResult&) = delete;
40 TaskWithResult& operator=(const TaskWithResult&) = delete;
41
44 TaskWithResult(TaskWithResult&& other) noexcept = default;
45
49 TaskWithResult& operator=(TaskWithResult&& other) noexcept = default;
50
57 T Get() noexcept(false) {
58 EnsureValid();
59
60 Wait();
61 const utils::FastScopeGuard invalidate([this]() noexcept { Invalidate(); });
62 if (GetState() == State::kCancelled) {
64 }
65
66 return utils::impl::CastWrappedCall<T>(GetPayload()).Retrieve();
67 }
68
71
73 static constexpr WaitMode kWaitMode = WaitMode::kSingleAwaiter;
74
75 // For internal use only.
76 explicit TaskWithResult(impl::TaskContextHolder&& context)
77 : Task(std::move(context))
78 {}
80
81 Task AsTask() && {
82 // NOLINTNEXTLINE(cppcoreguidelines-slicing)
83 return std::move(*this);
84 }
85
86private:
87 void EnsureValid() const {
89 IsValid(),
90 "TaskWithResult::Get was called on an invalid task. Note that "
91 "Get invalidates self, so it must be called at most once "
92 "per task"
93 );
94 }
95};
96
97} // namespace engine
98
99USERVER_NAMESPACE_END