如果我有可观察物a
,b
并且我想根据第三个可观察物在两者之间交替,那c
我将如何去做呢?大理石图如下所示:
a: -a1---------a2----a3--a4------a5--a6-----a7----
b: -b1--b2----b3--b4----------------b5---b6---b7--
c: --------c-----------c--------c----------c------
alternate
-a1--------b3--b4-----a4---------b5---b6-a7----
这很好用:
var query =
a.Publish(pa =>
b.Publish(pb =>
c.StartWith("c")
.Select((x, n) => n % 2 == 0 ? pa : pb)
.Switch()));
我使用以下代码进行了测试:
var xs = new []
{
"a1", "b1", "b2", "c", "b3",
"a2", "b4", "a3", "c", "a4",
"c", "a5", "b5", "a6", "b6",
"c", "a7", "b7",
}
.ToObservable()
.Publish();
var a = xs.Where(x => x.StartsWith("a"));
var b = xs.Where(x => x.StartsWith("b"));
var c = xs.Where(x => x.StartsWith("c"));
var query = ...
query.Subscribe(Console.WriteLine);
xs.Connect();
我得到了这个结果:
a1
b3
b4
a4
b5
b6
a7
在xs.Connect()
仅仅需要使xs
观察的工作作为一种简单的方法来产生三个序列。
甚至作为扩展方法:
public static IObservable<TSource> Alternate<TSource>(
this IObservable<TSource> leftSelector,
bool startLeft,
IObservable<TSource> left,
IObservable<TSource> right)
{
return
left.Publish(pl =>
right.Publish(pr =>
leftSelector.StartWith(default(TSource))
.Select((x, n) => (n % 2 == (startLeft ? 0 : 1)) ? pl : pr)
.Switch()));
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句