Line data Source code
1 : part of 'rx.dart'; 2 : 3 : /// class to add dynamic updates into a RxBuilder widget 4 : @sealed 5 : class RxNotifier<T> { 6 : // observable to listen the events from other observable localled in a RxBuilder Widget 7 : Rx<T?> subject = Rx(null); 8 : 9 : /// used to create a tmp RxNotifier since a RxBuilder Widget 10 : static RxNotifier? proxy; 11 : 12 : /// store the subscriptions for one observable 13 : final Map<Rx, List<StreamSubscription>> _subscriptions = {}; 14 4 : Map<Rx, List<StreamSubscription>> get subscriptions => _subscriptions; 15 : 16 : // used by the RxBuilder to check if the builder method contains an observable 17 6 : bool get canUpdate => subscriptions.isNotEmpty; 18 : 19 2 : void addListener(Rx<T> rx) { 20 : // if the current observable is not in the subscriptions 21 4 : if (!_subscriptions.containsKey(rx)) { 22 : // create a Subscription for this observable 23 10 : final StreamSubscription subs = rx.stream.listen(subject.controller.add); 24 : 25 : /// get the subscriptions for this Rx and add the new subscription 26 6 : final listSubscriptions = _subscriptions[rx] ?? []; 27 2 : listSubscriptions.add(subs); 28 4 : _subscriptions[rx] = listSubscriptions; 29 : } 30 : } 31 : 32 : /// used by the RxBuilder to listen the changes in a observable 33 2 : StreamSubscription<T?> listen(void Function(T?) _) { 34 6 : return subject.stream.listen(_); 35 : } 36 : 37 : /// Closes the subscriptions for this Rx, releasing the resources. 38 2 : FutureOr<void> close() async { 39 6 : for (final e in _subscriptions.values) { 40 4 : for (final subs in e) { 41 2 : await subs.cancel(); 42 : } 43 : } 44 4 : _subscriptions.clear(); 45 4 : return subject.close(); 46 : } 47 : }