bloc_stream 4.1.0 bloc_stream: ^4.1.0 copied to clipboard
A simple package that helps you to implement the BLoC pattern in your applications.
import 'package:bloc_stream/bloc_stream.dart';
class CounterActions {
static Stream<int> increment(int value, _) async* {
yield value + 1;
}
static Stream<int> decrement(int value, _) async* {
yield value - 1;
}
}
class CounterBloc extends BlocStream<int> {
@override
int get initialValue => 0;
}
int multiplyByThree(int i) => i * 3;
class MultiplicationActions {
static BlocStreamAction<int, MultiplicationBloc> multiply(input) =>
(_, _bloc) async* {
yield multiplyByThree(input);
};
}
class MultiplicationBloc extends BlocStream<int> {
MultiplicationBloc(CounterBloc counter) : _counter = counter {
// Bloc has a helper method for cleaning up subscriptions without having to
// write a boilerplate close() override.
cancelOnClose(counter.listen((count) {
add(MultiplicationActions.multiply(count));
}));
}
final CounterBloc _counter;
@override
int get initialValue => multiplyByThree(_counter.value);
}
void main() {
final counter = CounterBloc();
final multiplier = MultiplicationBloc(counter);
// Prints:
// 0
// MULTIPLY 0
// 1
// 2
// MULTIPLY 3
// 3
// MULTIPLY 6
// 2
// MULTIPLY 9
// 1
// MULTIPLY 6
// MULTIPLY 3
counter.distinct().listen(print);
multiplier.distinct().listen((i) => print('MULTIPLY $i'));
counter.add(CounterActions.increment);
counter.add(CounterActions.increment);
counter.add(CounterActions.increment);
counter.add(CounterActions.decrement);
counter.add(CounterActions.decrement);
}