我正在使用 Rx.Net 构建一个模拟。用户输入被建模为初始状态的状态转换流。使用Scan
我能够将这些转换解析为当前状态。
问题是转换可能有副作用。这些被建模为实现ISimulationEvent
.
我尝试了几种方法:
- 将副作用存储在当前状态对象中,并在每次转换时清除它们
- 返回一个
Tuple
游戏状态并IList<ISimulationEvent>
在Scan
- 传入副作用回调以聚合它们
每个解决方案都感觉“hacky”。
有没有一种干净的方法可以使用 Rx.Net 实现这一点?
这是我的命令如何折叠成状态的示例:
var commands = mouseStates
.DistinctUntilChanged(mouseState => mouseState.LeftButton)
.Where(mouseState => mouseState.LeftButton == ButtonState.Pressed)
.Select(mouseState => new CreateWidgetCommand(new Vector2(mouseState.X, mouseState.Y)));
var initialState = new SimulationState();
var states = commands.Scan(
initialState,
(state, command) => command.CanApply(state) ? command.Apply(state) : state);
每个都Apply
应该输出一个流ISimulationEvent
作为副作用。但是,我还需要保留结果SimulationState
。