block_cache.dart 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import 'dart:async';
  2. import 'package:flowy_sdk/log.dart';
  3. import 'package:flowy_sdk/protobuf/flowy-grid/block_entities.pb.dart';
  4. import '../field/field_cache.dart';
  5. import '../row/row_cache.dart';
  6. import 'block_listener.dart';
  7. /// Read https://appflowy.gitbook.io/docs/essential-documentation/contribute-to-appflowy/architecture/frontend/grid for more information
  8. class GridBlockCache {
  9. final String gridId;
  10. final BlockPB block;
  11. late GridRowCache _rowCache;
  12. late GridBlockListener _listener;
  13. List<RowInfo> get rows => _rowCache.rows;
  14. GridRowCache get rowCache => _rowCache;
  15. GridBlockCache({
  16. required this.gridId,
  17. required this.block,
  18. required GridFieldController fieldController,
  19. }) {
  20. _rowCache = GridRowCache(
  21. gridId: gridId,
  22. block: block,
  23. notifier: GridRowFieldNotifierImpl(fieldController),
  24. );
  25. _listener = GridBlockListener(blockId: block.id);
  26. _listener.start((result) {
  27. result.fold(
  28. (changesets) => _rowCache.applyChangesets(changesets),
  29. (err) => Log.error(err),
  30. );
  31. });
  32. }
  33. Future<void> dispose() async {
  34. await _listener.stop();
  35. await _rowCache.dispose();
  36. }
  37. void addListener({
  38. required void Function(RowsChangedReason) onRowsChanged,
  39. bool Function()? listenWhen,
  40. }) {
  41. _rowCache.onRowsChanged((reason) {
  42. if (listenWhen != null && listenWhen() == false) {
  43. return;
  44. }
  45. onRowsChanged(reason);
  46. });
  47. }
  48. }