helper.dart 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import 'dart:typed_data';
  2. import 'package:flowy_sdk/protobuf/flowy-dart-notify/protobuf.dart';
  3. import 'package:flowy_sdk/protobuf/flowy-user/protobuf.dart';
  4. import 'package:flowy_sdk/protobuf/flowy-workspace/errors.pb.dart';
  5. import 'package:flowy_sdk/protobuf/flowy-workspace/observable.pb.dart';
  6. import 'package:dartz/dartz.dart';
  7. typedef UserObservableCallback = void Function(UserObservable, Either<Uint8List, UserError>);
  8. class UserNotificationParser extends NotificationParser<UserObservable, UserError> {
  9. UserNotificationParser({required String id, required UserObservableCallback callback})
  10. : super(
  11. id: id,
  12. callback: callback,
  13. tyParser: (ty) => UserObservable.valueOf(ty),
  14. errorParser: (bytes) => UserError.fromBuffer(bytes),
  15. );
  16. }
  17. typedef NotificationCallback = void Function(Notification, Either<Uint8List, WorkspaceError>);
  18. class WorkspaceNotificationParser extends NotificationParser<Notification, WorkspaceError> {
  19. WorkspaceNotificationParser({required String id, required NotificationCallback callback})
  20. : super(
  21. id: id,
  22. callback: callback,
  23. tyParser: (ty) => Notification.valueOf(ty),
  24. errorParser: (bytes) => WorkspaceError.fromBuffer(bytes),
  25. );
  26. }
  27. class NotificationParser<T, E> {
  28. String id;
  29. void Function(T, Either<Uint8List, E>) callback;
  30. T? Function(int) tyParser;
  31. E Function(Uint8List) errorParser;
  32. NotificationParser({required this.id, required this.callback, required this.errorParser, required this.tyParser});
  33. void parse(ObservableSubject subject) {
  34. if (subject.id != id) {
  35. return;
  36. }
  37. final ty = tyParser(subject.ty);
  38. if (ty == null) {
  39. return;
  40. }
  41. if (subject.hasPayload()) {
  42. final bytes = Uint8List.fromList(subject.payload);
  43. callback(ty, left(bytes));
  44. } else if (subject.hasError()) {
  45. final bytes = Uint8List.fromList(subject.error);
  46. final error = errorParser(bytes);
  47. callback(ty, right(error));
  48. } else {
  49. // do nothing
  50. }
  51. }
  52. }