What are GetX Workers?
Workers in GetX are powerful tools that allow you to react to changes in reactive variables (Rx types). They execute side effects like logging, API calls, navigation, or any logic whenever the observed Rx variable changes. Workers are typically registered inside the onInit() method of a controller and are automatically disposed when the controller is destroyed.
- ever – React to Every Change
The ever worker triggers the callback every time the observed Rx variable changes. It's perfect for logging, saving data, or any action that should happen on every update.
- once – React Only Once
The once worker executes the callback only the first time the Rx variable changes. Subsequent changes are ignored. This is useful for one-time events like showing a tutorial or navigating after a condition is met.
- debounce – Wait for a Pause
The debounce worker waits for a specified period of inactivity before executing the callback. It's ideal for search inputs, form validations, or any scenario where you want to react after the user stops typing.
- interval – Trigger Periodically
The interval worker executes the callback at a fixed time interval while the Rx variable is changing. It's useful for throttling events, like tracking progress or limiting API calls during rapid changes.
- everAll – React to Multiple Variables
The everAll worker listens to a list of Rx variables and executes the callback whenever any of them changes. This is useful when you need to react to combined state.
- onceAll – Trigger Once When Any Changes
The onceAll worker triggers the callback the first time any of the observed Rx variables change. After that, it stops listening. This is great for onboarding or initial setup that should happen after user interaction.
Workers in Practice: Search with Debounce
Workers in Practice: Logging with ever
Best Practices
- Register workers in
onInit– This ensures they are set up when the controller is created. - Keep callbacks lightweight – Avoid heavy computations in workers; delegate to separate methods if needed.
- Use
debouncefor user input – Prevents excessive API calls during typing. - Dispose automatically – Workers are disposed when the controller is destroyed, no manual cleanup needed.
- Avoid infinite loops – Don't modify the same Rx variable inside its own worker without a guard condition.
- Combine with async/await – You can use
asynccallbacks, but be mindful of cancelled requests.
Common Mistakes
- ❌ Registering workers outside
onInit– May cause memory leaks if not properly managed. ✅ Always register inonInit. - ❌ Using
everwhendebounceis appropriate – Triggers on every keystroke, causing performance issues. ✅ Usedebouncefor search inputs. - ❌ Not handling async operations properly – Workers don't automatically cancel previous async tasks. ✅ Use a cancel token or ignore results from stale requests.
- ❌ Creating circular dependencies – Modifying the same Rx variable inside its worker can cause infinite loops. ✅ Use a flag to prevent recursion if needed.
- ❌ Forgetting to check for disposed controller – After async operations, check
Get.isRegisteredor useif (mounted)pattern. ✅ Useif (Get.isRegistered<MyController>())before accessing.
FAQ
- Q: Do workers automatically stop when the controller is disposed?
A: Yes, workers are tied to the controller's lifecycle and are automatically cleaned up when the controller is disposed. - Q: Can I use workers without a controller?
A: You can, but it's not recommended. Workers are meant to be used inside controllers to leverage automatic disposal and lifecycle. - Q: How do I handle async operations in workers?
A: You can use async callbacks, but be aware that if the Rx variable changes again before the async operation completes, you may get multiple overlapping calls. Consider usingdebounceor a cancel token. - Q: What's the difference between
debounceandinterval?
A:debouncewaits for a pause before executing;intervalexecutes repeatedly at a fixed rate while changes are happening. - Q: Can I remove a worker manually?
A: Workers are not directly removable, but since they're disposed with the controller, you can callGet.delete<MyController>()to remove the controller and its workers. - Q: Do workers work with
GetBuilder?
A: Workers listen to Rx variables, so they work regardless of whether you useObxorGetBuilder. They are independent of the UI. - Q: Can I use
everAllwith a mix of Rx types?
A: Yes,everAllaccepts a list of anyRxvariables, regardless of their type.
Conclusion
Workers are a powerful feature of GetX that allow you to react to state changes in a declarative and efficient way. By understanding ever, once, debounce, interval, and their all variants, you can build responsive applications with clean separation of concerns. Remember to register workers in onInit and keep side effects light for optimal performance.