-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: added a MultiListenerStreamController as an alternative to a Be…
…haviorSubject
1 parent
9fcf3f1
commit 18a75a3
Showing
3 changed files
with
57 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
import 'dart:async'; | ||
|
||
/// A simplified BehaviorSubject implementation | ||
class MultiListenerStreamController<T> { | ||
late T _value; | ||
bool _hasValue = false; | ||
|
||
final _controller = StreamController<T>.broadcast(); | ||
|
||
MultiListenerStreamController([T? initialValue]) { | ||
if (initialValue != null) { | ||
_value = initialValue; | ||
_hasValue = true; | ||
} | ||
} | ||
|
||
/// Get the current value | ||
T get value { | ||
if (!_hasValue) { | ||
throw StateError('No value has been emitted yet.'); | ||
} | ||
return _value; | ||
} | ||
|
||
/// Emit a new value | ||
void add(T newValue) { | ||
_value = newValue; | ||
_hasValue = true; | ||
_controller.add(newValue); | ||
} | ||
|
||
/// Listen to the stream | ||
Stream<T> get stream { | ||
return _controller.stream.transform( | ||
StreamTransformer.fromHandlers( | ||
handleData: (data, sink) { | ||
if (_hasValue) { | ||
sink.add(_value); // Emit the current value to new listeners | ||
} | ||
}, | ||
), | ||
); | ||
} | ||
|
||
/// Close the stream | ||
Future<void> close() => _controller.close(); | ||
|
||
/// Check if the stream is closed | ||
bool get isClosed => _controller.isClosed; | ||
} |