载入中...
搜索中...
未找到
Rx.h
浏览该文件的文档.
1#pragma once
2#include "common/Export.h"
3
4
5#include <functional>
6#include <memory>
7#include <mutex>
8#include <string>
9#include <vector>
10
11#include "common/Exception.h"
12
13namespace eve::rx {
14
22public:
24 enum class Type { Nil, Int, Float, Bool, String, Ptr };
25
26 Type type = Type::Nil;
27 int64_t i = 0;
28 double f = 0;
29 bool b = false;
30 std::string s;
31 void* p = nullptr;
32
34 static Value makeNil() { return {}; }
36 static Value makeInt(int64_t v) {
37 Value x;
38 x.type = Type::Int;
39 x.i = v;
40 return x;
41 }
43 static Value makeFloat(double v) {
44 Value x;
45 x.type = Type::Float;
46 x.f = v;
47 return x;
48 }
50 static Value makeBool(bool v) {
51 Value x;
52 x.type = Type::Bool;
53 x.b = v;
54 return x;
55 }
57 static Value makeString(std::string v) {
58 Value x;
59 x.type = Type::String;
60 x.s = std::move(v);
61 return x;
62 }
64 static Value makePtr(void* v) {
65 Value x;
66 x.type = Type::Ptr;
67 x.p = v;
68 return x;
69 }
70
72 bool isNil() const { return type == Type::Nil; }
73 bool isInt() const { return type == Type::Int; }
74 bool isFloat() const { return type == Type::Float; }
75 bool isBool() const { return type == Type::Bool; }
76 bool isString() const { return type == Type::String; }
77 bool isPtr() const { return type == Type::Ptr; }
78
80 int64_t toInt() const;
81 double toFloat() const;
82 bool toBool() const;
83 std::string toString() const;
84
86 bool equals(const Value& o) const;
87};
88
94public:
96 Subscription() = default;
98 explicit Subscription(std::function<void()> dispose) : dispose_(std::move(dispose)) {}
99 Subscription(const Subscription&) = delete;
102 Subscription(Subscription&& other) noexcept : dispose_(std::move(other.dispose_)), disposed_(other.disposed_) {
103 other.dispose_ = nullptr;
104 other.disposed_ = true;
105 }
108 if (this != &other) {
110 dispose();
111 dispose_ = std::move(other.dispose_);
112 disposed_ = other.disposed_;
113 other.dispose_ = nullptr;
114 other.disposed_ = true;
115 }
116 return *this;
117 }
120
122 void dispose() {
123 if (dispose_ && !disposed_) {
124 disposed_ = true;
125 auto fn = std::move(dispose_);
126 dispose_ = nullptr;
128 fn();
129 }
130 }
132 bool isDisposed() const { return disposed_; }
133
134private:
135 std::function<void()> dispose_;
136 bool disposed_ = false;
137};
138
144template <typename T>
146class Observer {
147public:
148 using NextFn = std::function<void(const T&)>;
149 using ErrorFn = std::function<void(const std::string&)>;
150 using CompletedFn = std::function<void()>;
151
158
160 bool isStopped() const { return stopped_; }
162 void setStopped() const { stopped_ = true; }
163
165 void next(const T& v) const {
166 if (!stopped_ && onNext) onNext(v);
167 }
169 void error(const std::string& e) const {
170 if (stopped_) return;
171 stopped_ = true;
172 if (onError) onError(e);
173 }
175 void completed() const {
176 if (stopped_) return;
177 stopped_ = true;
179 }
180
181private:
182 mutable bool stopped_ = false;
183};
184
185namespace detail {
186
187// Operators share these closure types per output T instead of generating new
188// std::function managers/invokers at every lambda expression. Keep separate
189// Observer copies, matching the original error/completion lambda captures.
190template <typename T>
191struct ForwardError {
193 void operator()(const std::string& error) const { out.error(error); }
194};
195
196template <typename T>
197struct ForwardCompleted {
199 void operator()() const { out.completed(); }
200};
201
202} // namespace detail
203
208template <typename T>
211public:
213 virtual ~Observable() = default;
214
217
220 Observer<T> obs;
221 obs.onNext = std::move(next);
223 return subscribe(std::move(obs));
224 }
228 typename Observer<T>::CompletedFn completed) {
229 Observer<T> obs;
230 obs.onNext = std::move(next);
231 obs.onError = std::move(error);
232 obs.onCompleted = std::move(completed);
234 return subscribe(std::move(obs));
235 }
236
238 Observable<T>* filter(std::function<bool(const T&)> pred);
240 template <typename R>
242 Observable<R>* map(std::function<R(const T&)> fn);
253};
254
256template <typename T>
259public:
263 : fn_(std::move(fn)) {}
265 Subscription subscribe(Observer<T> obs) override { return fn_(std::move(obs)); }
266
267private:
268 std::function<Subscription(Observer<T>)> fn_;
269};
270
271// ---- Operators ----
272template <typename T>
274Observable<T>* Observable<T>::filter(std::function<bool(const T&)> pred) {
275 auto* self = this;
276 return new AnonymousObservable<T>([self, pred](Observer<T> out) {
277 Observer<T> in;
278 in.onNext = [out, pred](const T& v) {
279 if (pred(v)) out.next(v);
280 };
281 in.onError = detail::ForwardError<T>{out};
282 in.onCompleted = detail::ForwardCompleted<T>{out};
283 return self->subscribe(std::move(in));
284 });
285}
286
287template <typename T>
288template <typename R>
290Observable<R>* Observable<T>::map(std::function<R(const T&)> fn) {
291 auto* self = this;
292 return new AnonymousObservable<R>([self, fn](Observer<R> out) {
293 Observer<T> in;
294 in.onNext = [out, fn](const T& v) { out.next(fn(v)); };
295 in.onError = detail::ForwardError<R>{out};
296 in.onCompleted = detail::ForwardCompleted<R>{out};
297 return self->subscribe(std::move(in));
298 });
299}
300
301template <typename T>
304 auto* self = this;
305 return new AnonymousObservable<T>([self, n](Observer<T> out) {
306 auto remaining = std::make_shared<int>(n);
307 Observer<T> in;
308 in.onNext = [out, remaining](const T& v) {
309 if (*remaining <= 0) return;
310 *remaining -= 1;
311 out.next(v);
312 if (*remaining == 0) {
313 out.completed();
314 // note: upstream keeps running; completed() already stopped `out`
315 }
316 };
317 in.onError = detail::ForwardError<T>{out};
318 in.onCompleted = detail::ForwardCompleted<T>{out};
319 return self->subscribe(std::move(in));
320 });
321}
322
323template <typename T>
326 auto* self = this;
327 return new AnonymousObservable<T>([self, n](Observer<T> out) {
328 auto remaining = std::make_shared<int>(n);
329 Observer<T> in;
330 in.onNext = [out, remaining](const T& v) {
331 if (*remaining > 0) {
332 *remaining -= 1;
333 return;
334 }
335 out.next(v);
336 };
337 in.onError = detail::ForwardError<T>{out};
338 in.onCompleted = detail::ForwardCompleted<T>{out};
339 return self->subscribe(std::move(in));
340 });
341}
342
343template <typename T>
346 auto* self = this;
347 return new AnonymousObservable<T>([self](Observer<T> out) {
348 auto done = std::make_shared<bool>(false);
349 Observer<T> in;
350 in.onNext = [out, done](const T& v) {
351 if (*done) return;
352 *done = true;
353 out.next(v);
354 out.completed();
355 };
356 in.onError = detail::ForwardError<T>{out};
357 in.onCompleted = detail::ForwardCompleted<T>{out};
358 return self->subscribe(std::move(in));
359 });
360}
361
362template <typename T>
365 auto* self = this;
366 return new AnonymousObservable<T>([self, other](Observer<T> out) {
367 Observer<T> in;
368 in.onNext = [out](const T& v) { out.next(v); };
369 in.onError = detail::ForwardError<T>{out};
370 in.onCompleted = detail::ForwardCompleted<T>{out};
371 auto src = std::make_shared<Subscription>(self->subscribe(std::move(in)));
372
373 Observer<T> stopper;
374 stopper.onNext = [out, src](const T&) mutable {
375 out.completed();
376 src->dispose();
377 };
378 stopper.onCompleted = [out, src]() mutable {
379 out.completed();
380 src->dispose();
381 };
382 auto stop = std::make_shared<Subscription>(other->subscribe(std::move(stopper)));
383
385 return Subscription([src, stop]() mutable {
386 src->dispose();
387 stop->dispose();
388 });
389 });
390}
391
392template <typename T>
395 auto* self = this;
396 return new AnonymousObservable<T>([self](Observer<T> out) {
397 auto last = std::make_shared<T>();
398 auto has = std::make_shared<bool>(false);
399 Observer<T> in;
400 in.onNext = [out, last, has](const T& v) {
401 if (*has && *last == v) return;
402 *has = true;
403 *last = v;
404 out.next(v);
405 };
406 in.onError = detail::ForwardError<T>{out};
407 in.onCompleted = detail::ForwardCompleted<T>{out};
408 return self->subscribe(std::move(in));
409 });
410}
411
416template <typename T>
418class Subject : public Observable<T> {
419public:
420 using Observable<T>::subscribe;
422 ~Subject() override = default;
423
426 auto slot = std::make_shared<Slot>();
427 slot->observer = std::move(obs);
428 {
430 std::lock_guard<std::mutex> lock(mu_);
431 if (stopped_) {
432 // Terminal state: deliver the terminal notification immediately
433 // to a fresh copy of the observer and never register the slot.
434 Observer<T> snapshot = slot->observer;
435 snapshot.completed();
436 return Subscription{};
437 }
438 slots_.push_back(slot);
439 }
441 return Subscription([this, slot]() { removeSlot(slot); });
442 }
443
445 void onNext(const T& v) { emit(Notification::Next, std::addressof(v)); }
447 void onError(const std::string& e) {
448 emit(Notification::Error, nullptr, &e);
449 markStopped();
450 }
452 void onCompleted() {
453 emit(Notification::Completed);
454 markStopped();
455 }
456
458 bool hasObservers() const {
460 std::lock_guard<std::mutex> lock(mu_);
461 for (const auto& s : slots_)
462 if (!s->removed) return true;
463 return false;
464 }
466 int observerCount() const {
468 std::lock_guard<std::mutex> lock(mu_);
469 int n = 0;
470 for (const auto& s : slots_)
471 if (!s->removed) n++;
472 return n;
473 }
474
475private:
476 struct Slot {
478 bool removed = false;
479 };
480
481 // The set of notifications is fixed: avoid three std::function closure
482 // managers/invokers per T merely to select the observer method.
483 enum class Notification { Next, Error, Completed };
484
485 void emit(Notification notification, const T* value = nullptr, const std::string* error = nullptr) {
486 std::vector<std::shared_ptr<Slot>> copy;
487 {
488 std::lock_guard<std::mutex> lock(mu_);
489 for (auto& s : slots_)
490 if (!s->removed) copy.push_back(s);
491 }
492 for (auto& s : copy) {
493 Observer<T> snapshot = s->observer;
494 switch (notification) {
495 case Notification::Next: snapshot.next(*value); break;
496 case Notification::Error: snapshot.error(*error); break;
497 case Notification::Completed: snapshot.completed(); break;
498 }
499 }
500 }
501
502 void removeSlot(const std::shared_ptr<Slot>& slot) {
503 std::lock_guard<std::mutex> lock(mu_);
504 slot->removed = true;
505 }
506
507 void markStopped() {
508 std::lock_guard<std::mutex> lock(mu_);
509 stopped_ = true;
510 slots_.clear();
511 }
512
513 mutable std::mutex mu_;
514 std::vector<std::shared_ptr<Slot>> slots_;
515 bool stopped_ = false;
516};
517
522template <typename T>
524class BehaviorSubject : public Observable<T> {
525public:
526 using Observable<T>::subscribe;
528 explicit BehaviorSubject(T initial) : latest_(std::move(initial)) {}
529
532 T latest;
533 bool replay = false;
534 {
536 std::lock_guard<std::mutex> lock(mu_);
537 if (!completed_) {
538 latest = latest_;
539 replay = true;
540 }
541 }
542 if (replay) obs.next(latest);
543 return base_.subscribe(std::move(obs));
544 }
545
547 T getValue() const {
549 std::lock_guard<std::mutex> lock(mu_);
550 return latest_;
551 }
553 void setValue(T v) {
554 T emitted;
555 {
557 std::lock_guard<std::mutex> lock(mu_);
558 latest_ = std::move(v);
559 emitted = latest_;
560 }
561 base_.onNext(emitted);
562 }
564 void onNext(T v) { setValue(std::move(v)); }
566 void onError(const std::string& e) {
567 {
569 std::lock_guard<std::mutex> lock(mu_);
570 completed_ = true;
571 }
572 base_.onError(e);
573 }
575 void onCompleted() {
576 {
578 std::lock_guard<std::mutex> lock(mu_);
579 completed_ = true;
580 }
581 base_.onCompleted();
582 }
584 bool hasObservers() const { return base_.hasObservers(); }
585
586private:
587 mutable std::mutex mu_;
588 T latest_;
589 bool completed_ = false;
590 Subject<T> base_;
591};
592
597template <typename T>
599class ReplaySubject : public Observable<T> {
600public:
601 using Observable<T>::subscribe;
603 explicit ReplaySubject(int capacity = 0) : capacity_(capacity) {}
604
607 std::vector<T> replay;
608 {
610 std::lock_guard<std::mutex> lock(mu_);
611 replay = buffer_;
612 }
613 for (const auto& v : replay)
614 if (!obs.isStopped()) obs.next(v);
615 return base_.subscribe(std::move(obs));
616 }
617
619 void onNext(T v) {
620 T emitted = v;
621 {
623 std::lock_guard<std::mutex> lock(mu_);
624 buffer_.push_back(std::move(v));
625 if (capacity_ > 0 && static_cast<int>(buffer_.size()) > capacity_)
626 buffer_.erase(buffer_.begin());
627 }
628 base_.onNext(emitted);
629 }
631 void onError(const std::string& e) {
632 base_.onError(e);
633 }
635 void onCompleted() {
636 base_.onCompleted();
637 }
639 bool hasObservers() const { return base_.hasObservers(); }
640
641private:
642 mutable std::mutex mu_;
643 std::vector<T> buffer_;
644 int capacity_;
645 Subject<T> base_;
646};
647
652template <typename T>
655public:
657 explicit ReactiveProperty(T initial = T()) : subject_(std::move(initial)) {}
658
660 T get() const { return subject_.getValue(); }
662 void set(T v) { subject_.setValue(std::move(v)); }
663
665 Subscription subscribe(Observer<T> obs) { return subject_.subscribe(std::move(obs)); }
667 Subscription subscribe(typename Observer<T>::NextFn next) { return subject_.subscribe(std::move(next)); }
668
670 BehaviorSubject<T>* asSubject() { return &subject_; }
672 Observable<T>* asObservable() { return &subject_; }
673
674private:
675 BehaviorSubject<T> subject_;
676};
677
678} // namespace eve::rx
double x
int observer
Definition AnimSmr.cpp:162
const std::string & s
glm::vec4 p[6]
#define EVENGINE_API_PLATFORM
Definition Export.h:107
std::uint32_t capacity
glm::vec3 n
Definition Grass.cpp:63
float v
bool done
Snapshot snapshot
MeleePoint3 b
Definition MeleeHit.cpp:41
std::string error
Definition Package.cpp:174
float f
Object::Ptr value
int detail
std::string slot
int removed
ScriptStructure out
Internal: observable built directly from a subscribe function.
Definition Rx.h:258
Subscription subscribe(Observer< T > obs) override
Subscribe.
Definition Rx.h:265
AnonymousObservable(std::function< Subscription(Observer< T >)> fn)
Constructs a AnonymousObservable.
Definition Rx.h:261
Subject that replays the latest value to every new subscriber. setValue()/onNext() update the stored ...
Definition Rx.h:524
void onCompleted()
Stops replay and delivers a terminal completion.
Definition Rx.h:575
bool hasObservers() const
True while at least one live observer is registered.
Definition Rx.h:584
T getValue() const
Current stored value.
Definition Rx.h:547
void onNext(T v)
Alias of setValue().
Definition Rx.h:564
void onError(const std::string &e)
Stops replay and delivers a terminal error.
Definition Rx.h:566
void setValue(T v)
Stores a new value and pushes it to observers.
Definition Rx.h:553
BehaviorSubject(T initial)
Creates a subject with an initial (replayed) value.
Definition Rx.h:528
Subscription subscribe(Observer< T > obs) override
Replays the latest value, then subscribes the observer.
Definition Rx.h:531
Push-based stream source. Operators return a new (caller-owned) Observable; subscribe() returns a Sub...
Definition Rx.h:210
virtual Subscription subscribe(Observer< T > obs)=0
Subscribes with a full observer; returns a cancel handle.
Observable< T > * filter(std::function< bool(const T &)> pred)
Passes values through only when pred(v) is true.
Definition Rx.h:274
Observable< T > * distinctUntilChanged()
Suppresses consecutive duplicate values (uses operator==).
Definition Rx.h:394
Observable< T > * takeUntil(Observable< T > *other)
Stops the stream when other emits or completes.
Definition Rx.h:364
Observable< R > * map(std::function< R(const T &)> fn)
Transforms each value with fn.
Definition Rx.h:290
virtual ~Observable()=default
Releases Observable resources.
Subscription subscribe(typename Observer< T >::NextFn next)
Subscribes with a value callback only.
Definition Rx.h:219
Observable< T > * skip(int n)
Drops the first n values.
Definition Rx.h:325
Observable< T > * take(int n)
Emits at most the first n values, then completes.
Definition Rx.h:303
Observable< T > * first()
Emits only the first value, then completes.
Definition Rx.h:345
Subscription subscribe(typename Observer< T >::NextFn next, typename Observer< T >::ErrorFn error, typename Observer< T >::CompletedFn completed)
Subscribes with value/error/completed callbacks.
Definition Rx.h:226
Callback bundle pushed to a subscriber. Once error() or completed() fires the observer is stopped and...
Definition Rx.h:146
CompletedFn onCompleted
Completion callback (terminal).
Definition Rx.h:157
void error(const std::string &e) const
Delivers a terminal error and stops.
Definition Rx.h:169
std::function< void(const T &)> NextFn
Definition Rx.h:148
void completed() const
Delivers a terminal completion and stops.
Definition Rx.h:175
NextFn onNext
Value callback.
Definition Rx.h:153
std::function< void(const std::string &)> ErrorFn
Definition Rx.h:149
bool isStopped() const
True after error()/completed() (or setStopped()).
Definition Rx.h:160
ErrorFn onError
Error callback (terminal).
Definition Rx.h:155
std::function< void()> CompletedFn
Definition Rx.h:150
void next(const T &v) const
Delivers a value unless stopped.
Definition Rx.h:165
void setStopped() const
Manually marks the observer stopped (used by operators).
Definition Rx.h:162
Observable value backed by a BehaviorSubject. get() returns the current value; set() stores and pushe...
Definition Rx.h:654
ReactiveProperty(T initial=T())
Creates a property with an initial value.
Definition Rx.h:657
BehaviorSubject< T > * asSubject()
Underlying behavior subject / observable view.
Definition Rx.h:670
T get() const
Current value.
Definition Rx.h:660
void set(T v)
Stores a new value and notifies subscribers.
Definition Rx.h:662
Subscription subscribe(typename Observer< T >::NextFn next)
Subscribe.
Definition Rx.h:667
Subscription subscribe(Observer< T > obs)
Subscribes with a full observer or a value callback.
Definition Rx.h:665
Observable< T > * asObservable()
As observable.
Definition Rx.h:672
Subject that buffers up to capacity values (0 = unlimited) and replays the buffer to every new subscr...
Definition Rx.h:599
ReplaySubject(int capacity=0)
Creates a replaying subject with the given buffer capacity.
Definition Rx.h:603
void onNext(T v)
Buffers and pushes a new value to observers.
Definition Rx.h:619
Subscription subscribe(Observer< T > obs) override
Replays buffered values, then subscribes the observer.
Definition Rx.h:606
void onCompleted()
Delivers a terminal completion to observers.
Definition Rx.h:635
void onError(const std::string &e)
Delivers a terminal error to observers.
Definition Rx.h:631
bool hasObservers() const
True while at least one live observer is registered.
Definition Rx.h:639
Multicast push-based stream: both an Observable and a push source. Thread-safe: onNext/onError/onComp...
Definition Rx.h:418
int observerCount() const
Number of live (non-disposed) observers.
Definition Rx.h:466
~Subject() override=default
Releases Subject resources.
Subscription subscribe(Observer< T > obs) override
Registers an observer; returns a Subscription that unregisters it.
Definition Rx.h:425
bool hasObservers() const
True while at least one live observer is registered.
Definition Rx.h:458
void onCompleted()
Pushes a terminal completion and stops the subject.
Definition Rx.h:452
void onNext(const T &v)
Pushes a value to every registered observer.
Definition Rx.h:445
void onError(const std::string &e)
Pushes a terminal error and stops the subject.
Definition Rx.h:447
RAII-style dispose handle for an active stream subscription. Disposing unsubscribes from the source; ...
Definition Rx.h:93
void dispose()
Runs the dispose callback once; idempotent.
Definition Rx.h:122
Subscription(std::function< void()> dispose)
Wraps a dispose callback (usually unsubscribing from a Subject).
Definition Rx.h:98
bool isDisposed() const
True once dispose() has run (or the handle was moved from).
Definition Rx.h:132
Subscription & operator=(Subscription &&other) noexcept
Operator =.
Definition Rx.h:107
~Subscription()
Releases Subscription resources.
Definition Rx.h:119
Subscription(const Subscription &)=delete
Subscription & operator=(const Subscription &)=delete
Subscription()=default
Constructs a Subscription.
Subscription(Subscription &&other) noexcept
Constructs a Subscription.
Definition Rx.h:102
Runtime variant used by the script-facing (Squirrel) streams. The C++ core is templated (Observer<T>/...
Definition Rx.h:21
Type type
Definition Rx.h:26
bool isNil() const
Type predicates.
Definition Rx.h:72
bool isInt() const
Definition Rx.h:73
static Value makeFloat(double v)
Constructs a floating-point value.
Definition Rx.h:43
bool isFloat() const
Definition Rx.h:74
static Value makeNil()
Constructs a nil value.
Definition Rx.h:34
bool isString() const
Definition Rx.h:76
static Value makePtr(void *v)
Constructs a pointer value (borrowed, not owned).
Definition Rx.h:64
std::string s
Definition Rx.h:30
Type
Type public API.
Definition Rx.h:24
static Value makeInt(int64_t v)
Constructs an integer value.
Definition Rx.h:36
static Value makeString(std::string v)
Constructs a string value (takes ownership).
Definition Rx.h:57
bool isBool() const
Definition Rx.h:75
bool isPtr() const
Definition Rx.h:77
static Value makeBool(bool v)
Constructs a boolean value.
Definition Rx.h:50
Definition Rx.cpp:13
enum EVENGINE_API_FOUNDATION Float
OT_FLOAT.
Definition Runtime.h:118
enum EVENGINE_API_FOUNDATION Bool
OT_BOOL.
Definition Runtime.h:116
enum EVENGINE_API_FOUNDATION String
OT_STRING.
Definition Runtime.h:119
SettlementPipeline::Stage fn