Skip to content

Instantly share code, notes, and snippets.

@PlugFox
Last active August 27, 2024 14:40
Show Gist options
  • Save PlugFox/d2afc6bd33c138e9ef0e6c74f405c779 to your computer and use it in GitHub Desktop.
Save PlugFox/d2afc6bd33c138e9ef0e6c74f405c779 to your computer and use it in GitHub Desktop.
Behavior distinct
/*
* Behavior distinct
* https://gist.github.com/PlugFox/d2afc6bd33c138e9ef0e6c74f405c779
* https://dartpad.dev?id=d2afc6bd33c138e9ef0e6c74f405c779
* Mike Matiunin <[email protected]>, 27 August 2024
*/
// ignore_for_file: avoid_print
import 'dart:async';
void main() {
final subject = BehaviorSubject.seed(0)..add(1);
final subscription = _subscribeDistinctPrint(subject, fix: true);
print('Current value: ${subject.value}\n'
'Emits:');
subject
..add(1)
..add(2)
..add(3)
..add(4)
..close();
Timer(Duration.zero, () {
subscription.cancel();
subject.close();
});
}
StreamSubscription<T> _subscribeDistinctPrint<T>(
BehaviorSubject<T> subject, {
bool fix = false,
}) {
if (fix) {
final value = subject.value;
return () async* {
yield value;
yield* subject.stream;
}()
.distinct()
.skip(1)
.listen(print);
} else {
return subject._controller.stream.distinct().listen(print);
}
}
final class BehaviorSubject<T> implements Sink<T> {
BehaviorSubject.seed(this._value);
final StreamController<T> _controller = StreamController<T>();
Stream<T> get stream => _controller.stream;
T _value;
T get value => _value;
@override
void add(T event) => _controller.add(_value = event);
@override
void close() => _controller.close();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment