ReactiveSubject<T> class
A wrapper class for RxDart subjects that provides a simplified interface for reactive programming.
This class encapsulates either a BehaviorSubject or a PublishSubject and provides methods to interact with the underlying subject in a more convenient way.
Usage:
// Create a ReactiveSubject with an initial value
final subject = ReactiveSubject<int>(initialValue: 0);
// Add a value
subject.add(1);
// Listen to the stream
subject.stream.listen((value) => print(value));
// Get the current value
print(subject.value);
// Dispose when done
subject.dispose();
Usage with StreamBuilder in a widget:
class MyWidget extends StatefulWidget {
@override
_MyWidgetState createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
final ReactiveSubject<int> _counter = ReactiveSubject<int>(initialValue: 0);
@override
void dispose() {
_counter.dispose();
super.dispose();
}
void _incrementCounter() {
_counter.add(_counter.value + 1);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: StreamBuilder<int>(
stream: _counter.stream,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text('Counter: ${snapshot.data}');
} else {
return CircularProgressIndicator();
}
},
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
child: Icon(Icons.add),
),
);
}
}
Constructors
- ReactiveSubject({T? initialValue})
- Creates a ReactiveSubject with a BehaviorSubject.
- ReactiveSubject.broadcast({T? initialValue})
- Creates a ReactiveSubject with a PublishSubject.
Properties
- hashCode → int
-
The hash code for this object.
no setterinherited
- isClosed → bool
-
Whether the underlying subject is closed.
no setter
- runtimeType → Type
-
A representation of the runtime type of the object.
no setterinherited
-
sink
→ Sink<
T> -
The sink of the underlying subject.
no setter
-
stream
→ Stream<
T> -
The stream of the underlying subject.
no setter
- value → T
-
The current value of the subject.
no setter
Methods
-
add(
T value) → void - Adds a new value to the subject.
-
addError(
Object error, [StackTrace? stackTrace]) → void - Adds an error to the subject.
-
dispose(
) → void - Closes the underlying subject.
-
noSuchMethod(
Invocation invocation) → dynamic -
Invoked when a nonexistent method or property is accessed.
inherited
-
toString(
) → String -
A string representation of this object.
inherited
Operators
-
operator ==(
Object other) → bool -
The equality operator.
inherited