once<T> function

Worker once<T>(
  1. RxInterface<T> listener,
  2. dynamic callback(
    1. T
    ),
  3. {dynamic condition}
)

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, Function(T) callback,
    {dynamic condition}) {
  Worker ref;
  StreamSubscription sub;
  sub = listener.subject.stream.listen((event) {
    if (!_conditional(condition)) return;
    ref._disposed = true;
    ref._log('called');
    sub?.cancel();
    callback(event);
  });
  ref = Worker(sub.cancel, '[once]');
  return ref;
}