flutter - BehaviorSubject 添加相同的值

标签 flutter dart rxdart

您好,我有一个具有简单类型 int 的 BehaviorSubject,我将值 5 添加到它,然后添加另一个值 5。流监听器向我发送了两个事件。 如果值等于最后一个值,如何强制检查值并且不发送事件。 示例代码:

    class TestBloc {
  TestBloc(){
    testBehavior.stream.listen((event) {
      print('Event value = $event');
    });
    addValueToStream();
    addValueToStream();
  }

  final testBehavior = BehaviorSubject<int>();

  void addValueToStream() {
    testBehavior.add(5);
  }
}

最佳答案

您正在寻找的是 BehaviorSubject()distinct() 方法。

从文档中看一下:

Skips data events if they are equal to the previous data event.

The returned stream provides the same events as this stream, except that it never provides two consecutive data events that are equal. That is, errors are passed through to the returned stream, and data events are passed through if they are distinct from the most recently emitted data event.

下面是你如何实现它:

class TestBloc {
  TestBloc() {
    testBehavior.distinct((a, b) => a == b).listen((event) {
      print('Event value = $event');
    });
    addValueToStream();
    addValueToStream();
  }

  final testBehavior = BehaviorSubject<int>();

  void addValueToStream() {
    testBehavior.add(5);
  }
}

关于flutter - BehaviorSubject 添加相同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66671769/

相关文章:

dart - Flutter 在图像上绘制并缩放并移动两者

flutter - 通过 Firebase 使用 Google 登录时, 'ApiExpception: 7' 是什么意思?

dart - 如何将 "scrollTarget"传递到 "core-list"/滚动

firebase - 使用 rxDart 合并 Firestore 流

stream - 基于 Dart/Flutter 中的过滤器更新流

flutter - 触摸通知后,如何转到屏幕的通知者滚动位置?

flutter -> 找不到 com.google.gms.google-services :4. 3.15 :. 要求者:项目:

charts - _ScaffoldLayout 自定义多子布局委托(delegate)忘记布局以下子级

dart - 如何在 flutter 中降级 rxdart 插件?

flutter - 抖动错误:未为 'combineLatest4'类型定义 'Observable'方法