[wpilib] SendableChooser: Add onChange listener (#5458)

This commit is contained in:
Gold856
2023-07-18 19:33:45 -04:00
committed by GitHub
parent 6f7cdd460e
commit 0b91ca6d5a
6 changed files with 98 additions and 6 deletions

View File

@@ -48,6 +48,13 @@ auto SendableChooser<T>::GetSelected()
}
}
template <class T>
requires std::copy_constructible<T> && std::default_initializable<T>
void SendableChooser<T>::OnChange(std::function<void(T)> listener) {
std::scoped_lock lock(m_mutex);
m_listener = listener;
}
template <class T>
requires std::copy_constructible<T> && std::default_initializable<T>
void SendableChooser<T>::InitSendable(nt::NTSendableBuilder& builder) {
@@ -95,11 +102,23 @@ void SendableChooser<T>::InitSendable(nt::NTSendableBuilder& builder) {
nullptr);
builder.AddStringProperty(kSelected, nullptr,
[=, this](std::string_view val) {
std::scoped_lock lock(m_mutex);
m_haveSelected = true;
m_selected = val;
for (auto& pub : m_activePubs) {
pub.Set(val);
T choice{};
std::function<void(T)> listener;
{
std::scoped_lock lock(m_mutex);
m_haveSelected = true;
m_selected = val;
for (auto& pub : m_activePubs) {
pub.Set(val);
}
if (m_previousVal != val && m_listener) {
choice = m_choices[val];
listener = m_listener;
}
m_previousVal = val;
}
if (listener) {
listener(choice);
}
});
}