RX中没有主题的反馈回路

Lou*_*fre 5 reactive-programming rxjs

我有以下运动方程式

move = target_position - position
position = position + move
Run Code Online (Sandbox Code Playgroud)

其中target_position是流,位置初始化为零。我希望有一个职位。我已经尝试过这样的事情(在rx伪代码中)

moves = Subject()
position = moves.scan(sum,0)
target_position.combine_latest(position,diff).subscribe( moves.on_next)
Run Code Online (Sandbox Code Playgroud)

它有效,但我已阅读应避免使用Subject。没有主题可以计算位置流吗?

在python中,完整的实现如下所示

from pprint import pprint 
from rx.subjects import Subject

target_position = Subject()

moves = Subject()

position = moves.scan(lambda x,y: x+y,0.0)

target_position\
    .combine_latest(position,compute_next_move)\
    .filter(lambda x: abs(x)>0)\
    .subscribe( moves.on_next)

position.subscribe( lambda x: pprint("position is now %s"%x))

moves.on_next(0.0)
target_position.on_next(2.0)
target_position.on_next(3.0)
target_position.on_next(4.0)
Run Code Online (Sandbox Code Playgroud)

Ben*_*esh 4

您可以使用展开运算符

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);
Run Code Online (Sandbox Code Playgroud)