有没有更符合思想的方法来通过某个谓词分割流? [英] Is there an more ideomatic way to split a stream by some predicate?

查看:35
本文介绍了有没有更符合思想的方法来通过某个谓词分割流?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个事件流,我想根据事件可能具有的某些属性将其拆分为多个流.类似下面的内容

I have a stream of events, which I want to split into multiple streams, based on some property the event may have. Something like the following

let streams = new rx.Subject()
let stream = new rx.Subject()
input.subscribe((x) => {
  stream.onNext(x)
  if (!x.splitHere) return
  streams.onNext(stream)
  stream = new rx.Subject()
})

编辑感谢您提供有关 partitionif 的提示.虽然他们确实将一个流拆分为多个,但他们只提供了两个结果流.

EDIT Thank you for the hints about partition and if. While they do split one stream into multiple, they only provide two result streams.

澄清我需要做的是将一个流切割成可变数量的流,切割点由谓词定义.

Clarification What I need to do is to cut one stream into a variable number of streams, and the incision point be defined by the predicate.

# partition
in    a---b---a---a---b--------b----a---
out1  a-------a---a-----------------a---
out2  ----b-----------b--------b--------

# what I need is to cut after every X
in      a-b-c-X-d-e-f-g-h-X-i-X-j-k-l-m-n-
out v   a-b-c-X
    v          -d-e-f-g-h-X
    v                      -i-X
    v                          -j-k-l-m-n-

推荐答案

window 做到这一点.

const streams = input
  .filter(x => x !== 'X')
  .window(input.filter(x => x === 'X'));

使用 partition 和数组解构你可以得到一些(在我看来)很好读的东西:

Using partition and array destructuring you can get something that (in my opinion) reads very nicely:

const [ incisions, items ] = input.partition(x => x === 'X');
const streams = items.window(incisions);

这篇关于有没有更符合思想的方法来通过某个谓词分割流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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