简体   繁体   English

转一个IObservable <IEnumerable<T> &gt;进入IEnumerable <IObservable<T> &gt;

[英]Turn an IObservable<IEnumerable<T>> into an IEnumerable<IObservable<T>>

How would I turn an observable of an enumerable xys into an enumerable of observables yxs , where each observable of yxs focuses on a particular element of each time step of xys ? 我怎么会变成可观察到的一个枚举的xys到观测的枚举yxs ,其中每个观测到的yxs重点中的每一步的特定元素xys What I want is similar to transposition for an enumerable of enumerables. 我想要的是类似于可枚举的可枚举的转置。

Example: 例:

IObservable<IEnumerable<int>> xys = Observable.Generate(0, _ => true, i => ++i, i => new[] {0 + i, 1 + i, 2 + i});
// xys = emits {0,1,2}, {1,2,3}, ...
IEnumerable<IObservable<int>> yxs = new[]
{
    Observable.Generate(0, i=>true, i=> ++i, i=>i),
    Observable.Generate(1, i=>true, i=> ++i, i=>i),
    Observable.Generate(2, i=>true, i=> ++i, i=>i),
};
// yxs = {emits 0, 1, ...}, {emits 1, 2, ...}, {emits 2, 3, ...}

I'm specifically interested in a function which is already part of Rx. 我特别感兴趣的是一个已经属于Rx的功能。 Like the above example, infinite observables should be possible as well as infinite enumerables. 像上面的例子一样,无限可观测量应该是可能的以及无限的可枚举。

This converts your "types" correctly. 这会正确转换您的“类型”。 However, you can't change the semantics of when/how the elements are delivered underneath, so you're really just going to end up buffering and blocking no matter how you go about this. 但是,您无法更改元素何时/如何在下面传递的语义,因此无论您如何处理这些元素,您最终都将最终进行缓冲和阻止。

dest = source.ToEnumerable().Map(x => x.ToObservable());

This is what I came up with so far. 这是我到目前为止所提出的。 However, it's a self made solution, not part of Rx. 但是,它是一个自制的解决方案,而不是Rx的一部分。 I would appreciate far more if someone pointed me to a solution involving library functions. 如果有人向我指出涉及库函数的解决方案,我将不胜感激。

public static IEnumerable<IObservable<T>> ObserveElements<T>(this IObservable<IEnumerable<T>> obs)
{
    var i = 0;
    while (true)
    {
        var idx = i++;
        yield return from enumerable in obs
                     let x = enumerable.ElementAtOrDefault(idx)
                     where !Equals(x, default(T))
                     select x;
    }
}

Obviously, you would .Take() only as much observables as you need. 显然,你会.Take()只)尽可能多的可观察量。

In Haskell terms, I think it's actually an implementation of sequence for the IObservable monad, specialized to IEnumerable . 在Haskell术语中,我认为它实际上是IObservable monad的sequence实现,专门用于IEnumerable

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM