-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReactiveDataCoroutine.h
More file actions
110 lines (80 loc) · 2.58 KB
/
ReactiveDataCoroutine.h
File metadata and controls
110 lines (80 loc) · 2.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
#pragma once
#include <experimental\coroutine>
#include <iostream>
#include <string>
#include <thread>
#include <chrono>
#include "VoidCoroutine.h"
using namespace std;
using namespace std::experimental;
using namespace std::chrono_literals;
template<typename T>
class ReactiveDataCoroutine {
public:
struct promise_type {
T m_value;
ReactiveDataCoroutine get_return_object() {
return ReactiveDataCoroutine(HandleType::from_promise(*this));
}
auto initial_suspend() { return std::experimental::suspend_always{}; }
std::experimental::suspend_always final_suspend() { return {}; }
void return_value(T value) {
m_value = value;
}
};
using HandleType = std::experimental::coroutine_handle<promise_type>;
HandleType m_coroutine = nullptr;
explicit ReactiveDataCoroutine(std::experimental::coroutine_handle<promise_type> coroutine)
: m_coroutine(coroutine) {
}
~ReactiveDataCoroutine() {
if (m_coroutine) { m_coroutine.destroy(); }
}
ReactiveDataCoroutine() = default;
ReactiveDataCoroutine(ReactiveDataCoroutine const&) = delete;
ReactiveDataCoroutine& operator=(ReactiveDataCoroutine const&) = delete;
ReactiveDataCoroutine(ReactiveDataCoroutine&& other)
:m_coroutine(other.m_coroutine) {
other.m_coroutine = nullptr;
}
ReactiveDataCoroutine& operator=(ReactiveDataCoroutine&& other) {
if (&other != this) {
m_coroutine = other.m_coroutine;
other.m_coroutine = nullptr;
}
return *this;
}
T get() {
return m_coroutine.promise().m_value;
}
void set(T value) {
m_value = value;
m_set = true;
m_coroutine.resume();
}
struct awaiter;
awaiter operator co_await() noexcept {
awaiter returnObject = awaiter{ *this };
return returnObject;
}
struct awaiter {
ReactiveDataCoroutine& m_resumable;
awaiter(ReactiveDataCoroutine& resumable) noexcept
:m_resumable(resumable) {
}
bool await_ready() {
cout << "ReactiveDataCoroutine::await_ready\n";
return m_set;
}
void await_resume() {
cout << "ReactiveDataCoroutine::await_resume\n";
}
void await_suspend(coroutine_handle<> waitingCoroutine) {
cout << "ReactiveDataCoroutine::await_suspend\n";
m_resumable.m_waitingCoroutine = waitingCoroutine;
}
};
private:
coroutine_handle<> m_waitingCoroutine;
bool m_set = false;
};