如何用 observables 定义循环

pkt*_*pkt 5 reactive-programming system.reactive reactive-extensions-js rxjs

我正在尝试设置一个简单游戏的更新循环,并考虑到可观察性。顶层组件是一个模型,它接受输入命令并产生更新;和一个视图,它显示接收到的更新,并产生输入。孤立地看,两者都可以正常工作,有问题的部分是将两者放在一起,因为两者都依赖于另一个。

将组件简化为以下内容:

var view = function (updates) {
  return Rx.Observable.fromArray([1,2,3]);
};
var model = function (inputs) {
  return inputs.map(function (i) { return i * 10; });
};
Run Code Online (Sandbox Code Playgroud)

我把事情联系在一起的方式是这样的:

var inputBuffer = new Rx.Subject();
var updates = model(inputBuffer);
var inputs = view(updates);
updates.subscribe(
    function (i) { console.log(i); },
    function (e) { console.log("Error: " + e); },
    function () { console.log("Completed"); }
);
inputs.subscribe(inputBuffer);
Run Code Online (Sandbox Code Playgroud)

也就是说,我添加了一个主题作为输入流的占位符,并将模型附加到该主题上。然后,在构建视图之后,我将实际输入传递给占位符主题,从而关闭循环。

然而,我不禁感到这不是正确的做事方式。为此使用主题似乎有点矫枉过正。有没有办法用 publish() 或 defer() 或类似的方法做同样的事情?

更新:这是一个不太抽象的例子来说明我遇到的问题。下面你会看到一个简单的“游戏”的代码,玩家需要点击一个目标来击中它。目标可以出现在左侧或右侧,每当它被击中时,它就会切换到另一侧。看起来很简单,但我仍然觉得我错过了一些东西......

//-- Helper methods and whatnot
// Variables to easily represent the two states of the target
var left = 'left';
var right = 'right';
// Transition from one side to the other
var flip = function (side) {
  if (side === left) {
    return right;
  } else {
    return left;
  }
};
// Creates a predicate used for hit testing in the view
var nearby = function (target, radius) {
  return function (position) {
    var min = target - radius;
    var max = target + radius;
    return position >= min && position <= max;
  };
};
// Same as Observable.prototype.scan, but it also yields the initial value immediately.
var initScan = function (values, init, updater) {
  var initValue = Rx.Observable.return(init);
  var restValues = values.scan(init, updater);
  return initValue.concat(restValues);
};

//-- Part 1: From input to state --
var process = function (inputs) {
  // Determine new state based on current state and input
  var update = function(current, input) {
    // Input value ignored here because there's only one possible state transition
    return flip(current);
  };
  return initScan(inputs, left, update);
};
//-- Part 2: From display to inputs --
var display = function (states) {
  // Simulate clicks from the user at various positions (only one dimension, for simplicity)
  var clicks = Rx.Observable.interval(800)
      .map(function (v) {return (v * 5) % 30; })
      .do(function (v) { console.log("Shooting at: " + v)})
      .publish();
  clicks.connect();

  // Display position of target depending on the model
  var targetPos = states.map(function (state) {
    return state === left ? 5 : 25;
  });
  // Determine which clicks are hits based on displayed position
  return targetPos.flatMapLatest(function (target) {
    return clicks
        .filter(nearby(target, 10))
        .map(function (pos) { return "HIT! (@ "+ pos +")"; })
        .do(console.log);
  });
};

//-- Part 3: Putting the loop together 
/**
 * Creates the following feedback loop:
 * - Commands are passed to the process function to generate updates.
 * - Updates are passed to the display function to generates further commands.
 * - (this closes the loop)
 */
var feedback = function (process, display) {
  var inputBuffer = new Rx.Subject(),
      updates = process(inputBuffer),
      inputs = display(updates);
  inputs.subscribe(inputBuffer);
};
feedback(process, display);
Run Code Online (Sandbox Code Playgroud)

Lee*_*ell 3

我想我明白你想在这里实现什么:

  • 如何获得一系列沿一个方向输入模型的输入事件
  • 但是有一系列输出事件从模型馈送到视图的另一个方向

我相信这里的答案是您可能想要翻转您的设计。假设采用 MVVM 风格设计,模型不会了解输入序列,而是变得不可知。这意味着您现在拥有一个具有 InputRecieved/OnInput/ExecuteCommand 方法的模型,视图将使用输入值调用该方法。现在,您应该更容易处理“一个方向的命令”和“另一个方向的事件”模式。这里是对 CQRS 的致敬。

在过去 4 年里,我们在 WPF/Silverlight/JS 中的视图+模型上广泛使用了这种风格。

也许是这样的;

var model = function()
{
    var self = this;
    self.output = //Create observable sequence here

    self.filter = function(input) {
        //peform some command with input here
    };
}

var viewModel = function (model) {
    var self = this;
    self.filterText = ko.observable('');
    self.items = ko.observableArray();
    self.filterText.subscribe(function(newFilterText) {
        model.filter(newFilterText);
    });
    model.output.subscribe(item=>items.push(item));
};
Run Code Online (Sandbox Code Playgroud)

更新

感谢您发布完整的示例。看上去不错。我喜欢你的新initScan操作员,这似乎是 Rx 的明显遗漏。

我按照我可能编写的方式对您的代码进行了重组。我希望它有帮助。我所做的主要工作是将逻辑封装到模型中(翻转、附近等),并让视图将模型作为参数。然后我还必须向模型添加一些成员,而不仅仅是一个可观察的序列。然而,这确实允许我从视图中删除一些额外的逻辑并将其也放入模型中(命中逻辑)

//-- Helper methods and whatnot

// Same as Observable.prototype.scan, but it also yields the initial value immediately.
var initScan = function (values, init, updater) {
  var initValue = Rx.Observable.return(init);
  var restValues = values.scan(init, updater);
  return initValue.concat(restValues);
};

//-- Part 1: From input to state --
var process = function () {
  var self = this;
  var shots = new Rx.Subject();
  // Variables to easily represent the two states of the target
  var left = 'left';
  var right = 'right';
  // Transition from one side to the other
  var flip = function (side) {
    if (side === left) {
      return right;
    } else {
      return left;
    }
  };
  // Determine new state based on current state and input
  var update = function(current, input) {
    // Input value ignored here because there's only one possible state transition
    return flip(current);
  };
  // Creates a predicate used for hit testing in the view
  var isNearby = function (target, radius) {
    return function (position) {
      var min = target - radius;
      var max = target + radius;
      return position >= min && position <= max;
    };
  };

  self.shoot = function(input) { 
    shots.onNext(input); 
  };

  self.positions = initScan(shots, left, update).map(function (state) {
    return state === left ? 5 : 25;
  });

  self.hits = self.positions.flatMapLatest(function (target) {  
    return shots.filter(isNearby(target, 10));
  });
};
//-- Part 2: From display to inputs --
var display = function (model) {
  // Simulate clicks from the user at various positions (only one dimension, for simplicity)
  var clicks = Rx.Observable.interval(800)
      .map(function (v) {return (v * 5) % 30; })
      .do(function (v) { console.log("Shooting at: " + v)})
      .publish();
  clicks.connect();

  model.hits.subscribe(function(pos)=>{console.log("HIT! (@ "+ pos +")");});

  // Determine which clicks are hits based on displayed position
  model.positions(function (target) {
    return clicks
        .subscribe(pos=>{
          console.log("Shooting at " + pos + ")");
          model.shoot(pos)
        });
  });
};

//-- Part 3: Putting the loop together 
/**
 * Creates the following feedback loop:
 * - Commands are passed to the process function to generate updates.
 * - Updates are passed to the display function to generates further commands.
 * - (this closes the loop)
 */
var feedback = function (process, display) {
  var model = process();
  var view = display(model);
};
feedback(process, display);
Run Code Online (Sandbox Code Playgroud)