[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);
          }
        }
      }
    }
  }
})
复制代码

 

posted @   Zhentiw  阅读(627)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2019-01-21 [TypeScript] Use the TypeScript "unknown" type to avoid runtime errors
2019-01-21 [Angular] Control the dependency lookup with @Host, @Self, @SkipSelf and @Optional
2019-01-21 [Flutter] Creating, Importing & Using Dynamic Widgets from Other Files in a Flutter Application
2019-01-21 [Angular] Tree shakable provider
2019-01-21 [TypeScript] Custom data structures in TypeScript with iterators
2017-01-21 [TypeScript] Catch unsafe use of "this" in TypeScript functions
2015-01-21 [AngularJS] angular-schema-form -- 1
点击右上角即可分享
微信分享提示