我有一个源流,有时会发出某个哨兵值来指定新流的开始。我想将我的流转换为IObservable<IObservable<T>>
。谁能想到一种优雅的方式?
答案 0 :(得分:1)
这应该可以解决问题:
observable = observable
.Publish()
.RefCount();
var splitted = observable
.Window(observable.Where(x => x == SENTINEL))
.Select(c => c.Where(x => x != SENTINEL));
完整示例:
const int SENTINEL = -1;
var observable = Observable
.Interval(TimeSpan.FromMilliseconds(100))
.Select(x => x + 1)
.Take(12)
.Select(x => x % 5 == 0 ? SENTINEL : x) // Every fifth is a sentinel
.Publish()
.RefCount();
observable
.Window(observable.Where(x => x == SENTINEL))
.Select(c => c.Where(x => x != SENTINEL))
.Select((c, i) => c.Select(x => (i, x))) // Embed the index of the subsequence
.Merge() // Merge them again
.Do(x => Console.WriteLine($"Received: {x}"))
.Subscribe();
await observable.LastOrDefaultAsync(); // Wait it to end
输出:
已收到:(0,1)
收到:(0,2)
收到:(0,3)
收到:(0,4)
收到:(1,6)
收到:(1,7)
收到:(1,8)
收到:(1,9)
收到:(2,11)
收到:(2,12)