Created
April 13, 2020 13:38
-
-
Save roboncode/f49fd633fda32ecce03efc73e95a3eae to your computer and use it in GitHub Desktop.
Dart - BlocCounter Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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