Skip to content

Signal

Signal is reactive state that encapsulate a value changing over time. When the value of a signal changes, it automatically notifies its observers.

Syntax

Signal<T>(T initialValue);

Signal accepts this property:

  • initialValue: Initial value of T type that the it will hold.

Properties & Methods

Signal provides the following properties and methods:

  • value: A getter/setter that allows to read and write its state.
  • Methods inherited from RtState (Learn more here):

    • update : A method to notify changes after run a set of instructions.
    • refresh : A method to force to notify changes.
    • * bind : A method to bind an instance to it.
    • * unbind : A method to unbind an instance to it.
    • * dispose : A method to remove all listeners and free resources.

Usage

Declaration

Signal can be initialized using the constructor class:

final intSignal = Signal<int>(0);
final strSignal = Signal("initial value");
final userSignal = Signal(User());

Reading and writing the value

Signal has a value property that allows to read and write its state:

intSignal.value = 10;
print("Current state: ${intSignal.value}");

or also can use the callable function:

intSignal(10);
print("Current state: ${intSignal()}");

or simply use .toString() implicit to get its value as String:

print("Current state: $intSignal");

Updating the value

Use update method to notify changes after run a set of instructions:

userSignal.update((user) {
user.firstname = "Firstname";
user.lastname = "Lastname";
});

Use refresh method to force to notify changes.

userSignal.refresh();

Listening to changes

When value has changed, the Signal will emit the following events(learn about it here):

  • Lifecycle.willUpdate event is triggered before the value change or update , refresh methods have been invoked.
  • Lifecycle.didUpdate event is triggered after the value change or update , refresh methods have been invoked.

Example of listening to changes:

1
Rt.on(
2
mySignal,
3
Lifecycle.didUpdate,
4
(_, state) => print("State value has changed to: ${state.value}"),
5
);