Effect

  • Effect 是一个处理所有副作用的函数。它接收下面的参数
    • Action action
    • Context context
      • BuildContext context
      • T state
      • dispatch
      • isDisposed
  • 它主要包含四方面的信息
    • 接收来自 View 的“意图”,包括对应的生命周期的回调,然后做出具体的执行。
    • 它的处理可能是一个异步函数,数据可能在过程中被修改,所以我们应该通过 context.state 获取最新数据。
    • 如果它要修改数据,应该发一个 Action 到 Reducer 里去处理。它对数据是只读的,不能直接去修改数据。
    • 如果它的返回值是一个非空值,则代表自己优先处理,不再做下一步的动作;否则广播给其他组件的 Effect 部分,同时发送给 Reducer。

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

  • 示例代码
  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. }