Subjects
Learn about different stream subjects offered by the RxDart library to manage asynchronous data streams.
We'll cover the following...
We'll cover the following...
Subjects are StreamControllers but with additional features. RxDart provides us with two Subjects: BehaviorSubject and ReplaySubject. The main purpose of these subjects is to give context to new subscribers about the events they missed when they were not subscribed.
BehaviorSubject
The BehaviorSubject captures the latest item that has been added to the controller and emits that as the first item to any new listener.
final subject = BehaviorSubject<int>();print("Old subscriber:");subject.stream.listen(print); // prints 1, 2, 3subject.add(1);subject.add(2);subject.add(3);await Future.delayed(Duration(milliseconds: 100));print("New subscribers:");subject.stream.listen(print); // prints 3subject.stream.listen(print); // prints 3
Line 4: We create a listener to the
BehaviorSubjectcreated in line 1. This listener is subscribed tosubjectbefore any events are ...