gpt4 book ai didi

reactive-programming - RX 中没有主题的反馈循环

转载 作者:行者123 更新时间:2023-12-04 08:21:52 26 4
gpt4 key购买 nike

我有以下运动方程

move = target_position - position
position = position + move

其中 target_position 是一个流,位置初始化为零。我想有一个职位流。我尝试过这样的事情(在 rx 伪代码中)
moves = Subject()
position = moves.scan(sum,0)
target_position.combine_latest(position,diff).subscribe( moves.on_next)

它有效,但我读过应该避免使用 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)

最佳答案

您可以使用 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);

关于reactive-programming - RX 中没有主题的反馈循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32732019/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com