从合并序列中删除Observable

时间:2012-11-23 12:29:31

标签: wpf c#-4.0 system.reactive

我使用Observable.Merge组合多个序列并在UI中的单个视图中显示。用户可以选择在UI中添加或删除序列(提要)。虽然我使用Merge来组合Feed。我不确定如何从Merged序列中分离IObservable。目前我正在创建一个全新的IObservable,省略了我想要的提要。是否可以动态添加和删除ViewModel已订阅的IObsevable?

3 个答案:

答案 0 :(得分:1)

查看使用IObservable<IObservable<T>>然后使用Merge。这会自动允许您通过结束内部IObservable<T>来删除序列。简单。

答案 1 :(得分:1)

这样的东西也会起作用,但我怀疑有更简洁的方法。

class Merger<T>
{
    Subject<T> _merged = new Subject<T>();

    public IObservable<T> Merged { get { return _merged; } }

    public IDisposable Add(IObservable<T> newStream)
    {
        return newStream.Subscribe(_merged);
    }
}

要从合并流中删除某些内容,请丢弃IDisposable。

答案 2 :(得分:0)

这可能有助于您入门,但在重新连接时,因为b很冷,b将从头开始重启:

var a = Observable.Generate('A', x => x <= Char.MaxValue, x => ++x, x => x, x => TimeSpan.FromMilliseconds(200)).Select(x => "a: " + x).Publish();
var b = Observable.Generate('a', x => x <= Char.MaxValue, x => ++x, x => x, x => TimeSpan.FromMilliseconds(500)).Select(x => "b: " + x).Publish();

var merged = a.Merge(b).Publish();
var submerged = merged.Subscribe(x => x.Dump());

var subA = a.Connect();
var subB = b.Connect();
merged.Connect();

Task.Delay(2000).ContinueWith(t => subB.Dump("Disposing b.").Dispose());
Task.Delay(4000).ContinueWith(t => b.Connect()).ContinueWith(_ => "Reconnected to b");

修改

向合并的IO添加另一个'c':

var a = Observable.Generate('A', x => x <= Char.MaxValue, x => ++x, x => x, x => TimeSpan.FromMilliseconds(200)).Select(x => "a: " + x).Publish();
var b = Observable.Generate('a', x => x <= Char.MaxValue, x => ++x, x => x, x => TimeSpan.FromMilliseconds(500)).Select(x => "b: " + x).Publish();
var c = Observable.Generate('1', x => x <= Char.MaxValue, x => ++x, x => x, x => TimeSpan.FromMilliseconds(100)).Select(x => "c: " + x).Publish();

var merged = a.Merge(b).Merge(c).Publish();
var submerged = merged.Subscribe(x => x.Dump());

var subA = a.Connect();
var subB = b.Connect();
merged.Connect();

Task.Delay(2000).ContinueWith(t => subB.Dump("Disposing b.").Dispose());
Task.Delay(4000).ContinueWith(t => b.Connect()).ContinueWith(_ => "Reconnected to b".Dump());
Task.Delay(6000).ContinueWith(t => c.Connect()).ContinueWith(_ => "Connecting to c".Dump());