Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/jifalops/simple_observable
A minimal observable and debouncer that works with callbacks, Futures, Streams, or any combination of the three.
https://github.com/jifalops/simple_observable
Last synced: 2 months ago
JSON representation
A minimal observable and debouncer that works with callbacks, Futures, Streams, or any combination of the three.
- Host: GitHub
- URL: https://github.com/jifalops/simple_observable
- Owner: jifalops
- License: mit
- Created: 2018-10-22T19:03:23.000Z (over 6 years ago)
- Default Branch: master
- Last Pushed: 2021-03-05T03:08:21.000Z (almost 4 years ago)
- Last Synced: 2024-01-07T17:14:31.007Z (about 1 year ago)
- Language: Dart
- Size: 17.6 KB
- Stars: 5
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- License: LICENSE
Awesome Lists containing this project
README
![pub.dev](https://img.shields.io/badge/pub-v1.0.0-blue)
# simple_observable
Observe value changes using a `Future`, `Stream`, and/or a callback.
## Source
```dart
class Observable {
Observable({T initialValue, this.onChanged, this.checkEquality = true})
: _value = initialValue;/// If true, setting the [value] will only notifiy if the new value is different
/// than the current value.
final bool checkEquality;
final void Function(T value) onChanged;var _completer = Completer();
bool _canceled = false;
bool get canceled => _canceled;T _value;
/// The current value of this observable.
T get value => _value;
set value(T val) {
if (!canceled && (!checkEquality || _value != val)) {
_value = val;
// Delaying notify() allows the Future and Stream to update correctly.
Future.delayed(Duration(microseconds: 1), () => notify(val));
}
}/// Alias for [value] setter. Good for passing to a Future or Stream.
void setValue(T val) => value = val;@protected
@mustCallSuper
void notify(T val) {
if (onChanged != null) onChanged(val);
// Completing with a microtask allows a new completer to be constructed
// before listeners of [nextValue] are called, allowing them to listen to
// nextValue again if desired.
_completer.complete(Future.microtask(() => val));
_completer = Completer();
}Future get nextValue => _completer.future;
Stream get values async* {
while (!canceled) {
yield await nextValue;
}
}/// Permanently disables this observable. Further changes to [value] will be
/// ignored, the outputs [onChanged], [nextValue], and [values] will not be
/// called again.
@mustCallSuper
void cancel() => _canceled = true;
}
```