base_expand.dart 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import 'dart:async';
  2. extension LetExtension<T> on T {
  3. /// 类似 Kotlin 的 let 函数,允许对任意对象执行代码块
  4. R let<R>(R Function(T it) block) {
  5. return block(this);
  6. }
  7. }
  8. extension ApplyExtension<T> on T {
  9. /// 类似 Kotlin 的 apply 函数,允许对对象执行配置操作,并返回自身
  10. T apply(void Function(T it) block) {
  11. block(this);
  12. return this;
  13. }
  14. }
  15. extension AlsoExtension<T> on T {
  16. T also(void Function(T it) block) {
  17. block(this);
  18. return this;
  19. }
  20. }
  21. extension RunExtension<T> on T {
  22. R run<R>(R Function(T it) block) => block(this);
  23. }
  24. extension StreamBufferTimeExtension<T> on Stream<T> {
  25. /// 将流中的事件按时间窗口缓冲,每隔 [duration] 时间发送一次缓冲列表
  26. Stream<List<T>> bufferTime(Duration duration) {
  27. StreamController<List<T>>? controller;
  28. List<T> buffer = [];
  29. Timer? timer;
  30. controller = StreamController<List<T>>(
  31. onListen: () {
  32. timer = Timer.periodic(duration, (_) {
  33. if (buffer.isNotEmpty) {
  34. controller?.add(List.from(buffer));
  35. buffer.clear();
  36. }
  37. });
  38. // 监听原始流,收集事件到缓冲区
  39. listen(
  40. (event) => buffer.add(event),
  41. onError: (error) => controller?.addError(error),
  42. onDone: () {
  43. timer?.cancel();
  44. // 流结束时发送剩余缓冲事件
  45. if (buffer.isNotEmpty) {
  46. controller?.add(List.from(buffer));
  47. buffer.clear();
  48. }
  49. controller?.close();
  50. },
  51. );
  52. },
  53. onCancel: () {
  54. timer?.cancel();
  55. buffer.clear();
  56. },
  57. );
  58. // 返回控制器对应的 Stream,而不是控制器本身
  59. return controller.stream;
  60. }
  61. }