I have a strange issue with rxdart BehaviorSubject.
Normally BehaviorSubject should only emit the last value to the stream:
A special StreamController that captures the latest item that has been added to the controller, and emits that as the first item to any new listener.
But in my case it is emitting all the previous values on the stream too and I dont know why.
I have the following test bloc:
class TestBloc {
final _controller = BehaviorSubject.seeded([]);
Stream get stream$ => _controller.stream;
TestBloc(BehaviorSubject subject) {
subject.listen((e) {
print("listen $e");
_controller.add([e]);
});
}
}
With test case:
test("test bloc", () async {
final subject = BehaviorSubject();
final bloc = TestBloc(subject);
subject.add(1);
subject.add(2);
// Uncomment next line to make test pass
// await expectLater(subject.stream, emits(2));
// Test will fail here
await expectLater(bloc.stream$, emits([2]));
});
The test fails because all the events from the subject where emitted and not only the expected last:
Expected: should emit an event that [2]
Actual: <Instance of 'BehaviorSubject<List<dynamic>>'>
Which: emitted * []
* [1]
* [2]
which emitted an event that at location [0] is [] which shorter than expected
Is this an issue with rxdart or am I doing something wrong.
To my understanding the .add() call in the listener should have the same effect as calling add consecutive like in the test case but it seems not to.