Skip to content

Instantly share code, notes, and snippets.

@nboutin
Created February 18, 2023 20:27
Show Gist options
  • Save nboutin/7775e59e8f774336bf8aca5c3e545743 to your computer and use it in GitHub Desktop.
Save nboutin/7775e59e8f774336bf8aca5c3e545743 to your computer and use it in GitHub Desktop.
RAII subscribe unscribe
// https://www.youtube.com/watch?v=nLSm3Haxz0I
class EventSource
{
void add(Listener& listener);
void remove(Listener& listener);
public:
[[nodiscard]]
Subscription subscribe(Listener& listener) {
return Subscription(*this, listener); }
};
class EventSource::Subscription
{
Subscription(EventSource& source, Listener& listener)
: source_(source), listener_(listener)
{ source_.add_listener(listener_); }
~Subscription()
{ source_.remove(listener_);}
// special function members
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment