Line data Source code
1 : import 'dart:async'; 2 : 3 : import 'package:meta/meta.dart'; 4 : import 'package:rx_bloc/src/model/error_with_tag.dart'; 5 : import 'package:rxdart/rxdart.dart'; 6 : 7 : import '../model/loading_with_tag.dart'; 8 : import '../model/result.dart'; 9 : import 'loading_bloc.dart'; 10 : 11 : part '../extensions.dart'; 12 : 13 : // ignore: public_member_api_docs 14 : abstract class RxBlocTypeBase { 15 : /// Dispose all StreamControllers and Composite Subscriptions 16 : void dispose(); 17 : } 18 : 19 : /// A base class that handles all common BloC functionality such as 20 : /// 1. Loading State 21 : /// 2. Error State 22 : abstract class RxBlocBase { 23 : /// A loading bloc that holds the loading state of all handled result streams. 24 : /// 25 : /// To register a result stream either call: 26 : /// 27 : /// ```dart 28 : /// setLoadingStateHandler(resultStream); 29 : /// ``` 30 : /// 31 : /// or: 32 : /// 33 : /// ```dart 34 : /// setResultStateHandler(resultStream); 35 : /// ``` 36 : /// 37 : /// To get the stream of all loading states simply call: 38 : /// ``` 39 : /// _loadingBloc.isLoading 40 : /// ``` 41 : /// 42 : final LoadingBloc _loadingBloc = LoadingBloc(); 43 : 44 : /// The loading states with tags of all handled result streams. 45 1 : @protected 46 : Stream<LoadingWithTag> get loadingWithTagState => 47 3 : _loadingBloc.states.isLoadingWithTag; 48 : 49 : /// The loading states without tags of all handled result streams. 50 1 : @protected 51 3 : Stream<bool> get loadingState => _loadingBloc.states.isLoading; 52 : 53 : /// The loading states with tags of all handled result streams. 54 1 : @protected 55 : Stream<bool> loadingForTagState(String tag) => 56 3 : _loadingBloc.states.isLoadingForTag(tag); 57 : 58 : /// The errors of all handled result streams. 59 0 : @protected 60 : Stream<Exception> get errorState => 61 0 : _resultStreamExceptionsSubject.mapToException(); 62 : 63 : /// The errors of all handled result streams along with the tag 64 1 : @protected 65 : Stream<ErrorWithTag> get errorWithTagState => 66 2 : _resultStreamExceptionsSubject.mapToErrorWithTag(); 67 : 68 : final _resultStreamExceptionsSubject = BehaviorSubject<ResultError>(); 69 : 70 : final _compositeSubscription = CompositeSubscription(); 71 : 72 : /// Disposes all internally created streams 73 1 : void dispose() { 74 2 : _resultStreamExceptionsSubject.close(); 75 2 : _compositeSubscription.dispose(); 76 2 : _loadingBloc.dispose(); 77 : } 78 : } 79 : 80 : extension _StreamAsSharedStream<T> on Stream<T> { 81 1 : Stream<T> asSharedStream({bool shareReplay = true}) { 82 : if (shareReplay) { 83 1 : if (this is! ReplayStream<T>) { 84 1 : return this.shareReplay(maxSize: 1); 85 : } 86 1 : } else if (this is! PublishSubject<T>) { 87 1 : return share(); 88 : } 89 : 90 : return this; 91 : } 92 : }