app_bloc.dart 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import 'package:app_flowy/workspace/domain/i_app.dart';
  2. import 'package:flowy_log/flowy_log.dart';
  3. import 'package:flowy_sdk/protobuf/flowy-workspace/errors.pb.dart';
  4. import 'package:flowy_sdk/protobuf/flowy-workspace/view_create.pb.dart';
  5. import 'package:freezed_annotation/freezed_annotation.dart';
  6. import 'package:flutter_bloc/flutter_bloc.dart';
  7. import 'package:dartz/dartz.dart';
  8. part 'app_bloc.freezed.dart';
  9. class AppBloc extends Bloc<AppEvent, AppState> {
  10. final IApp iAppImpl;
  11. final IAppListenr listener;
  12. AppBloc({required this.iAppImpl, required this.listener}) : super(AppState.initial());
  13. @override
  14. Stream<AppState> mapEventToState(
  15. AppEvent event,
  16. ) async* {
  17. yield* event.map(
  18. initial: (e) async* {
  19. listener.start(viewsChangeCallback: _handleViewsOrFail);
  20. yield* _fetchViews();
  21. },
  22. createView: (CreateView value) async* {
  23. final viewOrFailed = await iAppImpl.createView(name: value.name, desc: value.desc, viewType: value.viewType);
  24. yield viewOrFailed.fold((view) => state, (error) {
  25. Log.error(error);
  26. return state.copyWith(successOrFailure: right(error));
  27. });
  28. },
  29. didReceiveViews: (e) async* {
  30. yield state.copyWith(views: e.views);
  31. },
  32. );
  33. }
  34. @override
  35. Future<void> close() async {
  36. await listener.stop();
  37. return super.close();
  38. }
  39. void _handleViewsOrFail(Either<List<View>, WorkspaceError> viewsOrFail) {
  40. viewsOrFail.fold(
  41. (views) => add(AppEvent.didReceiveViews(views)),
  42. (error) {
  43. Log.error(error);
  44. },
  45. );
  46. }
  47. Stream<AppState> _fetchViews() async* {
  48. final viewsOrFailed = await iAppImpl.getViews();
  49. yield viewsOrFailed.fold(
  50. (apps) => state.copyWith(views: apps),
  51. (error) {
  52. Log.error(error);
  53. return state.copyWith(successOrFailure: right(error));
  54. },
  55. );
  56. }
  57. }
  58. @freezed
  59. class AppEvent with _$AppEvent {
  60. const factory AppEvent.initial() = Initial;
  61. const factory AppEvent.createView(String name, String desc, ViewType viewType) = CreateView;
  62. const factory AppEvent.didReceiveViews(List<View> views) = ReceiveViews;
  63. }
  64. @freezed
  65. class AppState with _$AppState {
  66. const factory AppState({
  67. required bool isLoading,
  68. required List<View>? views,
  69. required Either<Unit, WorkspaceError> successOrFailure,
  70. }) = _AppState;
  71. factory AppState.initial() => AppState(
  72. isLoading: false,
  73. views: null,
  74. successOrFailure: left(unit),
  75. );
  76. }