once<T> function

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

once() will execute only 1 time when condition is met and cancel the subscription to the listener stream right after that. condition defines when callback is called, and can be a bool or a bool Function().

Sample:

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

  @override
  Future<void> onInit() async {
    worker = once(count, (value) {
      print("counter reached $value before 3 seconds.");
    }, condition: () => count() > 2);
    3.delay(worker.dispose);
  }
  void increment() => count + 1;
}

Implementation

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