RX 中没有主题的反馈循环 [英] Feedback loop without Subject in RX

查看:30
本文介绍了RX 中没有主题的反馈循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下运动方程

move = target_position - position
position = position + move

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

where target_position is a stream and position is initialized at zero. I would like to have a stream of position. I have tried something like this (in rx pseudo code)

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

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

It works but I have read that using Subject should be avoided. Is it possible to compute the position stream without Subject?

在python中,完整的实现是这样的

In python the full implementation looks like this

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)

推荐答案

你可以使用 扩展运算符

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);

这篇关于RX 中没有主题的反馈循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆