首页 > 解决方案 > 拆分 IObservable进入 IObservable>

问题描述

我有一个源流,它有时会发出某个标记值来指定新流的开始。我想将我的流转换为IObservable<IObservable<T>>. 谁能想到一个优雅的方式?

标签: system.reactive

解决方案


这应该可以解决问题:

    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)


推荐阅读