Skip to content

Commit

Permalink
fix: Made the MultiListenerStreamController more versatile by adding …
Browse files Browse the repository at this point in the history
…a streamOrNull, value, valueOrNull and hasValue property
  • Loading branch information
vanlooverenkoen committed Dec 22, 2024
1 parent 9bf13cb commit ad8b051
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 28 deletions.
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
# 0.5.1

## Fix

- Made the MultiListenerStreamController more versatile by adding a streamOrNull, value, valueOrNull and hasValue property

# 0.5.0

## Feat
Expand Down
53 changes: 25 additions & 28 deletions lib/src/util/stream/multi_listener_stream_controller.dart
Original file line number Diff line number Diff line change
@@ -1,50 +1,47 @@
import 'dart:async';

/// A simplified BehaviorSubject implementation
class MultiListenerStreamController<T> {
late T _value;
bool _hasValue = false;
class MultiListenerStreamController<T extends Object?> {
T? _value;

final _controller = StreamController<T>.broadcast();

MultiListenerStreamController([T? initialValue]) {
if (initialValue != null) {
_value = initialValue;
_hasValue = true;
}
_value = initialValue;
}

/// Get the current value
T get value {
if (!_hasValue) {
throw StateError('No value has been emitted yet.');
if (hasValue) {
return _value as T;
}
return _value;
throw StateError('No value has been emitted yet.');
}

/// Emit a new value
T? get valueOrNull => _value;

bool get hasValue => _value != null;

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
}
},
),
);
}
Stream<T> get stream => _controller.stream.transform(
StreamTransformer.fromHandlers(
handleData: (data, sink) {
if (hasValue) {
sink.add(_value as T);
}
},
),
);

Stream<T?> get streamOrNull => _controller.stream.transform(
StreamTransformer.fromHandlers(
handleData: (data, sink) => sink.add(_value),
),
);

/// Close the stream
Future<void> close() => _controller.close();

/// Check if the stream is closed
bool get isClosed => _controller.isClosed;
}

0 comments on commit ad8b051

Please sign in to comment.