Skip to content

Instantly share code, notes, and snippets.

@jeffersonfr
Last active February 2, 2024 13:45
Show Gist options
  • Save jeffersonfr/22409d7059e0cf945bc8ad37af61cb90 to your computer and use it in GitHub Desktop.
Save jeffersonfr/22409d7059e0cf945bc8ad37af61cb90 to your computer and use it in GitHub Desktop.
Implementing MutableState from Kotlin/MVVM
#include <functional>
template <typename T> struct MutableState;
template <typename T> struct State {
State(MutableState<T> &state) : mState{state} {}
virtual void observe(std::function<void(T const &)> callback) {
mState.mCallback = callback;
}
private:
MutableState<T> &mState;
};
template <typename T> struct MutableState : public State<T> {
friend class State<T>;
MutableState() : State<T>(*this) {}
void observe(std::function<void(T const &)> callback) override {
mCallback = callback;
}
void notify(T const &data) { mCallback(data); }
private:
std::function<void(T const &)> mCallback;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment