BehaviorSubject 添加相同的值

BehaviorSubject adding the same value

您好,我有一个简单类型为 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);
  }
}