BehaviorSubject adding the same value

Issue

Hi I have a BehaviorSubject with a simple type int, I add the value 5 to it and then add another value 5. The stream listener sent me two events.
How to force check the values and not send an event if the value is equal to the last value.
Sample code:

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

  final testBehavior = BehaviorSubject<int>();

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

Solution

What you’re looking for is distinct() method of BehaviorSubject().

Take a look at this from the documentation:

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.

and here is how you implement it:

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);
  }
}

Answered By – Stewie Griffin

Answer Checked By – Jay B. (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *