redux_machine 0.1.2 copy "redux_machine: ^0.1.2" to clipboard
redux_machine: ^0.1.2 copied to clipboard

Dart 1 only

Redux State Machine and Store with no side-effects.

example/main.dart

// Copyright (c) 2017, Anatoly Pulyaevskiy. All rights reserved. Use of this source code
// is governed by a BSD-style license that can be found in the LICENSE file.

import 'package:redux_machine/redux_machine.dart';

/// Implementation of a simple coin-operated turnstile state machine
/// as described here:
/// https://en.wikipedia.org/wiki/Finite-state_machine#Example:_coin-operated_turnstile
void main() {
  // Create our machine and register reducers:
  final builder = new StateMachineBuilder<Turnstile>(
      initialState: new Turnstile(true, 0, 0));
  builder
    ..bind(Actions.putCoin, putCoinReducer)
    ..bind(Actions.push, pushReducer);
  final machine = builder.build();

  // Try triggering some actions
  machine.dispatch(Actions.push());
  machine.dispatch(Actions.putCoin());
  machine.dispatch(Actions.push());
  machine.dispatch(Actions.push());
  machine.dispatch(Actions.push());
  machine.dispatch(Actions.push());
  machine.dispatch(Actions.putCoin());
  machine.dispatch(Actions.putCoin());
  machine.dispatch(Actions.push());
  machine.dispatch(Actions.push());
  // .. etc.
  // Make sure to dispose the machine in the end:
  machine.dispose();
}

class Turnstile {
  final bool isLocked;
  final int coinsCollected;
  final int visitorsPassed;

  Turnstile(this.isLocked, this.coinsCollected, this.visitorsPassed);

  /// Convenience method to use in reducers.
  Turnstile copyWith({
    bool isLocked,
    int coinsCollected,
    int visitorsPassed,
  }) {
    return new Turnstile(
      isLocked ?? this.isLocked,
      coinsCollected ?? this.coinsCollected,
      visitorsPassed ?? this.visitorsPassed,
    );
  }
}

abstract class Actions {
  /// Put coin to unlock turnstile
  static const ActionBuilder<Null> putCoin =
      const ActionBuilder<Null>('putCoin');

  /// Push turnstile to pass through
  static const ActionBuilder<Null> push = const ActionBuilder<Null>('push');
}

Turnstile putCoinReducer(
    Turnstile state, Action<Null> action, ActionDispatcher dispatcher) {
  int coinsCollected = state.coinsCollected + 1;
  print('Coins collected: $coinsCollected');
  return state.copyWith(isLocked: false, coinsCollected: coinsCollected);
}

Turnstile pushReducer(
    Turnstile state, Action<Null> action, ActionDispatcher dispatcher) {
  int visitorsPassed = state.visitorsPassed;
  if (!state.isLocked) {
    visitorsPassed++;
    print('Visitors passed: ${visitorsPassed}');
  }
  return state.copyWith(isLocked: true, visitorsPassed: visitorsPassed);
}
0
likes
30
pub points
0%
popularity

Publisher

unverified uploader

Redux State Machine and Store with no side-effects.

Repository (GitHub)
View/report issues

License

BSD-3-Clause (LICENSE)

More

Packages that depend on redux_machine