Line data Source code
1 : import 'dart:async'; 2 : 3 : import 'package:meta/meta.dart' show sealed; 4 : 5 : part 'rx_notifier.dart'; 6 : 7 : /// Rx class to work with observables 8 : class Rx<T> { 9 : /// Constructor 10 : /// 11 : /// creates a new observable with an initial value 12 5 : Rx(T initalValue) { 13 5 : _value = initalValue; 14 : } 15 : 16 : /// store the value for this observable 17 : late T _value; 18 : 19 : /// StreamController to emit the changes in the current observable 20 : StreamController<T>? _controller; 21 : 22 4 : StreamController<T> get controller { 23 8 : _controller ??= StreamController.broadcast(); 24 4 : return _controller!; 25 : } 26 : 27 : /// stream for the current observable 28 12 : Stream<T> get stream => controller.stream; 29 : 30 : /// returns true if the current observable has listeners 31 3 : bool get hasListeners => controller.hasListener; 32 : 33 : /// update the value and add a event sink to the [StreamController] 34 3 : set value(T newValue) { 35 6 : if (_value != newValue) { 36 3 : _value = newValue; 37 12 : controller.sink.add(_value); 38 : } 39 : } 40 : 41 : /// returns the current value for this observable 42 5 : T get value { 43 : // if we have a RxBuilder accessing to the current value 44 : // we add a listener for that Widget 45 : if (RxNotifier.proxy != null) { 46 2 : RxNotifier.proxy!.addListener(this); 47 : } 48 5 : return _value; 49 : } 50 : 51 : /// close the [StreaMeeduController] for this observable 52 12 : FutureOr<void> close() => _controller?.close(); 53 : }