【问题标题】:What to do when one stream depends on the value from another?当一个流依赖于另一个流的值时该怎么办?
【发布时间】:2016-01-20 01:34:27
【问题描述】:

我是 Rx.js 的新手,正在寻找有关 FRP 概念的一些基本帮助。我有一个使用generateWithRelativeTime 的流来保持游戏循环运行,还有一个流可以跟踪屏幕分辨率。我当前代码的问题是我的游戏循环仅在我的屏幕分辨率更改时运行。

我的模型函数生成的流需要 res$ 的最新值。

function model(res$) {
  return res$.map(res => {
    const rows = ceil(res[1] / CELL.HEIGHT)+1
    const cols = ceil(res[0] / CELL.WIDTH)+1

    return Observable.generateWithRelativeTime(
      initWorld(rows, cols, 1.618),
      noOp,
      world => step(world),
      noOp,
      _ => 100,
      Rx.Scheduler.requestAnimationFrame
    ).timeInterval()
  });
}

function intent() {
  return Observable.fromEvent(window, 'resize')
                   .map(e => [e.currentTarget.innerWidth, e.currentTarget.innerHeight])
                   .debounce(100, Rx.Scheduler.requestAnimationFrame)
                   .startWith([window.innerWidth, window.innerHeight])
}

model(intent())

【问题讨论】:

    标签: javascript system.reactive reactive-programming rxjs frp


    【解决方案1】:

    欢迎享受 FRP 的乐趣。事实上,很难理解你的问题。 What to do when one stream depends on the value from another? 是如何连接到 My problem with my current code is that my game loop only runs when my screen resolution changes. 的?你给出实际行为,你期望的行为是什么?

    由于我对这个问题的理解有限,我认为您需要将这一行return res$.map(res => { 替换为return res$.flatMapLatest(res => {,即使用运算符flatMapLatest 而不是map 运算符。

    要了解flatMap 运算符,我建议您查看以下资源:The introduction to reactive programming you've been missingillustrated marblesofficial documentation

    PS:我看到您似乎遵循 MODEL-VIEW-INTENT 架构。出于好奇,您是否正在尝试使用cyclejs

    【讨论】:

    • 谢谢!这实际上修复了它。预期的行为是游戏循环应该运行,并且每次运行时,使用 res$ 流中的最新分辨率。现在可以了 :) 谢谢!
    • 另外,是的,我正在玩 Cycle.js :)
    • 很好,您能否接受或投票赞成这个答案,以表明它对可能通过谷歌搜索偶然发现这个问题的其他读者是正确或有用的?
    猜你喜欢
    • 2021-04-24
    • 1970-01-01
    • 2011-03-10
    • 1970-01-01
    • 1970-01-01
    • 2020-09-29
    • 1970-01-01
    • 2020-04-21
    • 2017-12-08
    相关资源
    最近更新 更多