Workers
Learn to perform actions in reaction to events or state changes with the help of workers.
Introduction to workers
The beauty of reactive programming is that we do not have to worry about every event that occurs. We just have to define a scenario and write the code to handle that scenario. Workers in GetX are functions that allow us to define actions and map them to a
The ever
method
ever
is the most straightforward worker—it performs the action every time the value of the input variable changes. In the code snippet below, we define a reactive variable count
of type RxInt
(though any data type would do) and input it into the method. As for the action, we log an analytics event every time the value of count
changes.
// Reactive variablefinal RxInt count = 0.obs;// Logs analytics every time user changes the countever<int>(count, (value) => logAnalyticsEvent('Count changed to $value'));
We also need to provide the data type to the worker, which is int
in this case.
Condition
We get additional control over the updates with the condition
parameter. It is of dynamic
type, so we can provide it a bool directly or assign a callback that returns a bool. Below, we have added the condition that the value of count
should be greater than 5
.
ever<int>(count,(value) => logAnalyticsEvent('Count changed to $value'),condition: () => count.value > 5,);
In this case, the ...