Search⌘ K
AI Features

Subjects

Explore RxDart's Subjects, BehaviorSubject and ReplaySubject, to manage state effectively in Flutter. Learn how these enhance stream controllers by providing new subscribers with missed event data, allowing more efficient asynchronous event handling.

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.

Dart
final subject = BehaviorSubject<int>();
print("Old subscriber:");
subject.stream.listen(print); // prints 1, 2, 3
subject.add(1);
subject.add(2);
subject.add(3);
await Future.delayed(Duration(milliseconds: 100));
print("New subscribers:");
subject.stream.listen(print); // prints 3
subject.stream.listen(print); // prints 3
  • Line 4: We create a listener to the BehaviorSubject created in line 1. This listener is subscribed to subject before any events are ...