Effect

  • Effect is a function that handles all side effects. It receives the following parameters
    • Action action
    • Context context
      • BuildContext context
      • T state
      • dispatch
      • isDisposed
  • It mainly contains four aspects of information
    • Receive “intent” from the View, including the corresponding lifecycle callback, and then make specific execution.
    • Its processing may be an asynchronous function, the data may be changed in the process, so we should get the latest data through context.state.
    • If you want to modify the data, you should send an Action to the Reducer to handle. It is read-only for data and cannot be modified directly in a effect function.
    • If its return value is a non-null value, it will take precedence for itself and will not do the next step; otherwise it will broadcast to the Effect part of other components and sent the action to the Reducer.

Self-First-Broadcast。
image.png | left | 747x399

  • Sample Code
  1. /// one style of writing
  2. FutureOr<Object> sideEffect(Action action, Context<String> ctx) async {
  3. if (action.type == Lifecycle.initState) {
  4. //do something on initState
  5. return true;
  6. } else if (action.type == 'onShare') {
  7. //do something on onShare
  8. await Future<void>.delayed(Duration(milliseconds: 1000));
  9. ctx.dispatch(const Action('shared'));
  10. return true;
  11. }
  12. return null;
  13. }
  14. class MessageComponent extends Component<String> {
  15. MessageComponent(): super(
  16. view: buildMessageView,
  17. effect: sideEffect,
  18. );
  19. }
  1. /// another style of writing
  2. Effect<String> buildEffect() {
  3. return combineEffects(<Object, Effect<String>>{
  4. Lifecycle.initState: _initState,
  5. 'onShare': _onShare,
  6. });
  7. }
  8. void _initState(Action action, Context<String> ctx) {
  9. //do something on initState
  10. }
  11. void _onShare(Action action, Context<String> ctx) async {
  12. //do something on onShare
  13. await Future<void>.delayed(Duration(milliseconds: 1000));
  14. ctx.dispatch(const Action('shared'));
  15. }
  16. class MessageComponent extends Component<String> {
  17. MessageComponent(): super(
  18. view: buildMessageView,
  19. effect: buildEffect(),
  20. );
  21. }