ever<T> function

Worker ever<T>(
  1. RxInterface<T> listener,
  2. WorkerCallback<T> callback, {
  3. dynamic condition = true,
  4. Function? onError,
  5. void onDone()?,
  6. bool? cancelOnError,
})

Called every time listener changes. As long as the condition returns true.

Sample: Every time increment() is called, ever() will process the condition (can be a bool expression or a bool Function()), and only call the callback when condition is true. In our case, only when count is bigger to 5. In order to "dispose" this Worker that will run forever, we made a worker variable. So, when the count value reaches 10, the worker gets disposed, and releases any memory resources.

// imagine some counter widget...

class _CountController extends GetxController {
  final count = 0.obs;
  Worker worker;

  void onInit() {
    worker = ever(count, (value) {
      print('counter changed to: $value');
      if (value == 10) worker.dispose();
    }, condition: () => count > 5);
  }

  void increment() => count + 1;
}

Implementation

Worker ever<T>(
  RxInterface<T> listener,
  WorkerCallback<T> callback, {
  dynamic condition = true,
  Function? onError,
  void Function()? onDone,
  bool? cancelOnError,
}) {
  StreamSubscription sub = listener.listen(
    (event) {
      if (_conditional(condition)) callback(event);
    },
    onError: onError,
    onDone: onDone,
    cancelOnError: cancelOnError,
  );
  return Worker(sub.cancel, '[ever]');
}