app_bloc.dart 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import 'package:app_flowy/workspace/domain/i_app.dart';
  2. import 'package:flowy_sdk/protobuf/flowy-workspace/errors.pb.dart';
  3. import 'package:flowy_sdk/protobuf/flowy-workspace/view_create.pb.dart';
  4. import 'package:freezed_annotation/freezed_annotation.dart';
  5. import 'package:flutter_bloc/flutter_bloc.dart';
  6. import 'package:dartz/dartz.dart';
  7. part 'app_bloc.freezed.dart';
  8. class AppBloc extends Bloc<AppEvent, AppState> {
  9. final IApp iAppImpl;
  10. AppBloc(this.iAppImpl) : super(AppState.initial());
  11. @override
  12. Stream<AppState> mapEventToState(
  13. AppEvent event,
  14. ) async* {
  15. yield* event.map(
  16. initial: (e) async* {
  17. yield* _fetchViews();
  18. },
  19. createView: (CreateView value) async* {
  20. iAppImpl.createView(
  21. name: value.name, desc: value.desc, viewType: value.viewType);
  22. },
  23. );
  24. }
  25. Stream<AppState> _fetchViews() async* {
  26. final viewsOrFailed = await iAppImpl.getViews();
  27. yield viewsOrFailed.fold(
  28. (apps) => state.copyWith(views: some(apps)),
  29. (error) => state.copyWith(successOrFailure: right(error)),
  30. );
  31. }
  32. }
  33. @freezed
  34. abstract class AppEvent with _$AppEvent {
  35. const factory AppEvent.initial() = Initial;
  36. const factory AppEvent.createView(
  37. String name, String desc, ViewType viewType) = CreateView;
  38. }
  39. @freezed
  40. abstract class AppState implements _$AppState {
  41. const factory AppState({
  42. required bool isLoading,
  43. required Option<List<View>> views,
  44. required Either<Unit, WorkspaceError> successOrFailure,
  45. }) = _AppState;
  46. factory AppState.initial() => AppState(
  47. isLoading: false,
  48. views: none(),
  49. successOrFailure: left(unit),
  50. );
  51. }