pub struct Signal<T> { /* private fields */ }Expand description
A reactive signal that notifies listeners when its value changes.
§Bridging signals to the UI thread (async feature)
Signal is UI-thread-only (Rc internals, not Send) and listeners run
synchronously inside Signal::set/Signal::update. To drive widgets
from a signal, bridge the listener into the bounded UI command queue
instead of touching widgets directly:
- Create a
UiProxywithUi::task_proxybefore wiring the listener. - Subscribe once on the UI thread; the listener converts the new value
into proxy posts (
set_text,set_value,set_checked,set_enabled,set_visible,progress). AUiProxyisSendand bounded, so the same wiring works when the signal is updated on the UI thread and the commands are applied on the next event-loop turn. - Drain the queue from the event loop:
Ui::wait_event,Ui::poll_event,Ui::dispatch_events, andrun_until_closedapply posted commands in FIFO order on the UI thread before returning backend events.
Posts that arrive after teardown, or when the bounded queue is full,
report TaskSendError instead of blocking or
panicking, so a listener can degrade gracefully. Background threads cannot
hold a Signal: send raw values through the proxy (or a channel) and
update the signal on the UI thread, where its listeners run.
use native_gui_mock::MockBackend;
use native_gui_core::state::Signal;
use native_gui_core::{Ui, WidgetKind};
let mut ui = Ui::new(MockBackend::default());
let label = ui.create(WidgetKind::Label, Some("0"))?;
let proxy = ui.task_proxy();
let counter = Signal::new(0i32);
counter.subscribe(move |value| {
let _ = proxy.set_text(label, value.to_string());
});
counter.set(1);
// The queue drains on the next event-loop turn (here: a dispatch pass).
ui.dispatch_events(|_| {})?;
assert_eq!(
ui.widget(label).and_then(|spec| spec.text.clone()),
Some("1".to_owned())
);Implementations§
Source§impl<T: Clone + PartialEq> Signal<T>
impl<T: Clone + PartialEq> Signal<T>
Sourcepub fn set(&self, new_value: T)
pub fn set(&self, new_value: T)
Sets a new value for the signal, notifying listeners if the value changed.
Sourcepub fn update(&self, mutate: impl FnOnce(&mut T))
pub fn update(&self, mutate: impl FnOnce(&mut T))
Mutates the value in place and notifies listeners once if it changed.
This is the main entry point for the observable store: views subscribe
with Signal::subscribe and rebuild the affected widgets when the
value they depend on changes.