A dart package that helps implement the BLoC design pattern with the power of Dart Stream extended by the capabilities provided by RxDart library.
import 'package:token_bloc/token_bloc.dart';
/// A bloc that manages a counter.
class CounterBloc extends TokenBloc {
/// Creates a [CounterBloc] and sets the action handlers.
CounterBloc() {
/// When an [incrementCounterAction] is dispatched, the [_onIncrementAction] method is called.
onVoid(incrementCounterAction, _onIncrementAction);
/// When an [decrementCounterAction] is dispatched, the [_onDecrementAction] method is called.
onVoid(decrementCounterAction, _onDecrementAction);
}
/// The state of the counter with an initial value of 0.
final counterState = TokenState<int>.seeded(0);
/// The action to increment the counter.
final incrementCounterAction = TokenActionVoid();
/// The action to decrement the counter.
final decrementCounterAction = TokenActionVoid();
void _onIncrementAction() {
/// The current value of the counter is obtained with the [valueOf] method.
final newValue = valueOf(counterState) + 1;
/// The new value is emitted with the [emitStateOf] method.
emitStateOf(counterState, newValue);
}
void _onDecrementAction() {
final newValue = valueOf(counterState) - 1;
emitStateOf(counterState, newValue);
}
/// The [subjects] getter is used to obtain the token subjects that the bloc manages.
@override
List<TokenSubject<dynamic>> get subjects => [
counterState,
incrementCounterAction,
decrementCounterAction,
];
}
Future<void> main() async {
/// Create the `bloc`.
final bloc = CounterBloc();
/// Listen to the counter state changes.
bloc.counterState.listen((state) {
print('Counter: ${state.value}');
});
/// Dispatch the increment action.
bloc.incrementCounterAction();
/// Dispatch the decrement action.
bloc.decrementCounterAction();
/// Dispose the `bloc` when it is no longer needed.
await subscription.dispose();
}
We welcome contributions to this package. If you would like to contribute, please feel free to open an issue or a pull request.
To see a complete example, see the TokenBloc Example folder.
TokenBloc is licensed under the MIT License. See the LICENSE for details.