State Management
What is state management?
State management is the process of keeping track of the state of your application and providing a way to modify it.
Applications are usually just a giant event loop with logic. This means that you can't just change the state randomly and expect sane results. That's why there is state management.
A good state management system should be: reactive, fast and memoy efficient.
The Signal
System
Maycoon uses signals to manage state using listeners and thread-safe mechanics.
A signal is composed out of following components:
- a value, often but not always mutable.
- a list of listeners to notify when the value changes.
- a thread-safe way to modify the value.
Beware that not all signal types are mutable and some are merely side-effects.
Using Signal
The Signal
trait has many methods, but the most important ones are:
get
: Returns a reference to the inner value as aRef
enum.set
: Sets the inner value and notifies all listeners.notify
: Notifies all listeners attached to the signal.listen
: Attaches a listener to the signal.
In order to use signals, you must first "hook" them into the application lifecycle using Signal::hook
or AppContext::use_signal
like this:
#![allow(unused)] fn main() { // hook the signal into the application let value = context.use_signal(StateSignal::new("Hello World".to_string())); // use the signal inside a widget Text::new(MaybeSignal::signal(value)) }
MaybeSignal
is merely an enum which can be either a signal or a fixed value.
Passing signals to widgets using MaybeSignal::signal
can make these signals mutate over the lifetime of the application, depending on which widget you pass it to.
Do's and Dont's
Do...
- ...use signals sparingly and prefer
MaybeSignal::value
for fixed values. - ...use
Signal::hook
orAppContext::use_signal
to hook signals into the application. - ...use
MaybeSignal::signal
to pass signals to widgets. - ...use specific signals for specific needs.
- ...use signals for local state management.
Don't...
- ...use
Signal::set_value
directly to mutate values. - ...create signals without hooking them into the application.
- ...pass signals as mutable references.
- ...pass signals to widgets without using
MaybeSignal::signal
. - ...use signals for global state management.