zoukankan      html  css  js  c++  java
  • [XState] Invoke Callbacks to Send and Receive Events from a Parent XState Machine

    We can invoke a callback as a service when we enter a state in XState. This gives us the ability to trigger various functionality by responding to events sent to the service, and allows us to send events back to the parent machine.

    We do this by writing a "callback handler" and setting it as the src of our invoked service. A callback handler is a function that receives the current context and the event object that triggered the invocation. This function returns another function that receives two functions as arguments. A callback function to send events to the parent machine, and an onEvent function for the handler to respond to events sent to the handler.

    The way events are sent to the callback handler is by utilizing the options argument of the send action creator. We identify where we send events to using the to property, and setting the value to the id of our service.

    const handlerEchoCallback = (context, event) => {
      return (callback, onReceive) => {
        onReceive(e => {
          if (e.type === 'FOO') {
           callback('ECHO'); // call the 'ECHO' action
          }
        })
      }
    }
    
    const callbackMachine = Machine({
      id: 'callbackMachine',
      initial: 'listening',
      states: {
        listening: {
          invoke: {
            src: handlerEchoCallback,
            id: 'handlerEchoCallback'
          },
          on: {
            SPEAK: {
              actions: send('FOO', {
                to: 'handlerEchoCallback'
              })
            },
            ECHO: {
              actions: (context, event) => {
                console.log('echo', context, event);
              }
            }
          }
        }
      }
    })
  • 相关阅读:
    RFC-RTSP
    ISDN简记
    mysql:Cannot proceed because system tables used by Event Scheduler were found damaged at server start
    Linux下svn常用命令
    嵌入式开发者技能
    Lua和C的语法差别
    CubeMX使用及感受
    海康、大华IPC的rtsp格式
    环境小硕的转行之路-15-小作业、闭包、迭代器
    环境小硕的转行之路-14-动态传参、命名空间、nonlocal和global
  • 原文地址:https://www.cnblogs.com/Answer1215/p/12222589.html
Copyright © 2011-2022 走看看