app_bloc.dart 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import 'package:app_flowy/workspace/domain/i_app.dart';
  2. import 'package:flowy_infra/flowy_logger.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. AppBloc(this.iAppImpl) : super(AppState.initial());
  12. @override
  13. Stream<AppState> mapEventToState(
  14. AppEvent event,
  15. ) async* {
  16. yield* event.map(
  17. initial: (e) async* {
  18. yield* _fetchViews();
  19. },
  20. createView: (CreateView value) async* {
  21. iAppImpl.createView(
  22. name: value.name, desc: value.desc, viewType: value.viewType);
  23. },
  24. );
  25. }
  26. Stream<AppState> _fetchViews() async* {
  27. final viewsOrFailed = await iAppImpl.getViews();
  28. yield viewsOrFailed.fold(
  29. (apps) => state.copyWith(views: apps),
  30. (error) {
  31. Log.error(error);
  32. return state.copyWith(successOrFailure: right(error));
  33. },
  34. );
  35. }
  36. }
  37. @freezed
  38. abstract class AppEvent with _$AppEvent {
  39. const factory AppEvent.initial() = Initial;
  40. const factory AppEvent.createView(
  41. String name, String desc, ViewType viewType) = CreateView;
  42. }
  43. @freezed
  44. abstract class AppState implements _$AppState {
  45. const factory AppState({
  46. required bool isLoading,
  47. required List<View>? views,
  48. required Either<Unit, WorkspaceError> successOrFailure,
  49. }) = _AppState;
  50. factory AppState.initial() => AppState(
  51. isLoading: false,
  52. views: null,
  53. successOrFailure: left(unit),
  54. );
  55. }