Last active
February 2, 2024 13:45
-
-
Save jeffersonfr/22409d7059e0cf945bc8ad37af61cb90 to your computer and use it in GitHub Desktop.
Implementing MutableState from Kotlin/MVVM
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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