在RX中没有主题的反馈循环

时间:2015-09-23 05:57:09

标签: reactive-programming rxjs

我有以下运动方程式

exp of float -infinity: -1.#INF
exp of double -infinity: 0

其中target_position是流,位置初始化为零。我想有一个位置流。我尝试过类似的东西(在rx伪代码中)

move = target_position - position
position = position + move

它有效但我已经读过应该避免使用Subject。是否可以在没有主题的情况下计算位置流?

在python中,完整的实现看起来像这样

moves = Subject()
position = moves.scan(sum,0)
target_position.combine_latest(position,diff).subscribe( moves.on_next)

1 个答案:

答案 0 :(得分:1)

您可以使用expand operator

targetPosition.combineLatest(position, (target, current) => [target, current])
  .expand(([target, current]) => {
    // if you've reached your target, stop
    if(target === current) {
      return Observable.empty()
    }
    // otherwise, calculate the new position, emit it
    // and pump it back into `expand`
    let newPosition = calcPosition(target, current);
    return Observable.just(newPosition)
  })
  .subscribe(updateThings);