Skip to content

Commit

Permalink
feat: added a MultiListenerStreamController as an alternative to a Be…
Browse files Browse the repository at this point in the history
…haviorSubject
vanlooverenkoen committed Dec 22, 2024
1 parent 9fcf3f1 commit 18a75a3
Showing 3 changed files with 57 additions and 0 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.0

## Feat

- Added a MultiListenerStreamController that is a simplified version of the BehaviorSubject from RxDart

# 0.4.0

## Feat
1 change: 1 addition & 0 deletions lib/impaktfull_architecture.dart
Original file line number Diff line number Diff line change
@@ -23,6 +23,7 @@ export 'src/util/number_formatter/number_formatter_util.dart';
export 'src/util/storage/key_value/key_value_store.dart';
export 'src/util/storage/secure/secure_store.dart';
export 'src/util/storage/shared_prefs/shared_prefs_store.dart';
export 'src/util/stream/multi_listener_stream_controller.dart';
export 'src/widget/lifecycle/lifecycle_widget.dart';
export 'src/widget/mixin/after_layout.dart';
export 'src/widget/provider/provider_widget.dart';
50 changes: 50 additions & 0 deletions lib/src/util/stream/multi_listener_stream_controller.dart
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;
}

0 comments on commit 18a75a3

Please sign in to comment.