Skip to content

Instantly share code, notes, and snippets.

@roboncode
Created April 13, 2020 13:38
Show Gist options
  • Save roboncode/f49fd633fda32ecce03efc73e95a3eae to your computer and use it in GitHub Desktop.
Save roboncode/f49fd633fda32ecce03efc73e95a3eae to your computer and use it in GitHub Desktop.
Dart - BlocCounter Example
import 'dart:async';
enum CounterEvent {increment, decrement}
class CounterBloc {
int _counter = 0;
get state => _counter;
final _counterStateController = StreamController<int>();
StreamSink<int> get _inCounter => _counterStateController.sink;
Stream<int> get counter => _counterStateController.stream;
final _counterEventController = StreamController<CounterEvent>();
Sink<CounterEvent> get counterEventSink => _counterEventController.sink;
CounterBloc() {
_counterEventController.stream.listen(_mapEventToState);
}
void _mapEventToState(CounterEvent event) {
if (event == CounterEvent.increment) {
_counter++;
} else if (event == CounterEvent.decrement) {
_counter--;
}
_inCounter.add(_counter);
}
dispose() {
_counterStateController.close();
_counterEventController.close();
}
}
var decorateCounter = StreamTransformer<int, String>.fromHandlers(handleData: (int val, EventSink<String>sink) => {
sink.add('New counter is $val')
});
void main() {
final counterBloc = CounterBloc();
counterBloc.counter
.transform(decorateCounter)
.listen((val) => print(val));
counterBloc.counterEventSink.add(CounterEvent.increment);
counterBloc.counterEventSink.add(CounterEvent.decrement);
counterBloc.counterEventSink.add(CounterEvent.increment);
print(counterBloc.state);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment