【问题标题】:How to group and combine two streams based on the first?如何根据第一个流对两个流进行分组和组合?
【发布时间】:2016-09-20 03:19:18
【问题描述】:

我想根据第一个流的值对两个流进行分组和组合。用一个具体的例子来说明,

每当第一个流发生变化时,我想将值与第二个流合并,但跳过紧邻的下一个值(即图中的值 1、3 和 6)。

我在 iOS 上使用 ReactiveCocoa,但欢迎使用其他响应式框架的示例。

【问题讨论】:

    标签: javascript reactive-programming rxjs reactive-cocoa


    【解决方案1】:

    在 javascript 中,它会类似于(虽然未测试):

    const result$ = a$.flatMapLatest(a => b.skip(1).map(b => {a,b}))
    

    这应该做什么:

    • 对于每个传入的 a,监听 bs,跳过第一个 b,然后将 b 和 a 放在一起

    你的限制:

    • b 必须是热流

    顺便说一句,图不错。

    【讨论】:

      【解决方案2】:

      我目前在 ReactiveCocoa 中的实现:

      var cook = MutableProperty("")
      var ingredient = MutableProperty("")
      
      cook.signal.observeNext { cook in
          print(">", cook)
      }
      
      let skipFirst = cook.signal
          .flatMap(.latest) { cookValue in
              return ingredient.signal
                  .map { ingredientValue in
                      "\(cookValue) \(ingredientValue)"
                  }
                  .skip(first: 1)
          }
      
      skipFirst.observeNext { str in
          print(">>", str)
      }
      
      // Send values
      
      cook.value = "grill"
      ingredient.value = "asparagus"
      ingredient.value = "beef"
      
      cook.value = "fry"
      ingredient.value = "ice cream"
      ingredient.value = "donut"
      ingredient.value = "shoe"
      
      cook.value = "steam"
      ingredient.value = "egg"
      ingredient.value = "lettuce"
      

      打印出来:

      > grill
      >> grill beef
      > fry
      >> fry donut
      >> fry shoe
      > steam
      >> steam lettuce
      

      但这意味着如果我还想使用每个组的第一个值,我必须重复flatMap 转换,这看起来不是很干。

      cook.signal
          .flatMap(.latest) { cookValue in
              return ingredient.signal
                  .map { ingredientValue in
                      "\(cookValue) \(ingredientValue)"
                  }
                  .take(first: 1)
          }
          .observeNext { str in
              print("**>", str)
          }
      

      【讨论】:

        猜你喜欢
        • 2018-05-02
        • 2017-01-28
        • 2020-06-29
        • 2019-05-30
        • 1970-01-01
        • 1970-01-01
        • 2019-08-24
        • 1970-01-01
        • 2018-11-18
        相关资源
        最近更新 更多