Skip to content

Instantly share code, notes, and snippets.

@machinescream
Created October 26, 2019 22:41
Show Gist options
  • Save machinescream/d03d971a9d7a2ac61317466d845c0ec6 to your computer and use it in GitHub Desktop.
Save machinescream/d03d971a9d7a2ac61317466d845c0ec6 to your computer and use it in GitHub Desktop.
library example;
import 'dart:isolate';
import 'package:built_redux/built_redux.dart';
import 'package:built_value/built_value.dart';
part 'example.g.dart';
void main() async {
final receivePort = ReceivePort();
SendPort sendPort;
final isolate = await Isolate.spawn(_handleWithPorts, receivePort.sendPort);
receivePort.listen((dynamic message) {
if (message is SendPort) {
sendPort = message;
sendPort.send(ActionBundle(incr, 0));
} else {
print(message);
}
});
}
void incr(dynamic store) {
store.actions.increment(1);
}
abstract class CounterActions extends ReduxActions {
ActionDispatcher<int> get increment;
ActionDispatcher<int> get decrement;
CounterActions._();
factory CounterActions() => new _$CounterActions();
}
abstract class Counter implements Built<Counter, CounterBuilder> {
/// [count] value of the counter
int get count;
Counter._();
factory Counter() => new _$Counter._(count: 0);
}
void increment(Counter state, Action<int> action, CounterBuilder builder) =>
builder.count = state.count + action.payload;
void decrement(Counter state, Action<int> action, CounterBuilder builder) =>
builder.count = state.count - action.payload;
final reducerBuilder = new ReducerBuilder<Counter, CounterBuilder>()
..add(CounterActionsNames.increment, increment)
..add(CounterActionsNames.decrement, decrement);
void _handleWithPorts(SendPort sendPort) async {
final receivePort = ReceivePort();
sendPort.send(receivePort.sendPort);
final store = Store<Counter, CounterBuilder, CounterActions>(
reducerBuilder.build(),
Counter(),
CounterActions(),
);
await for (var message in receivePort) {
if (message is ActionBundle) {
message.func(store);
sendPort.send(store.state.count);
}
}
}
class ActionBundle {
final Function func;
final Object data;
ActionBundle(this.func, this.data);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment