Rx.NET“门”运算符

时间:2018-06-03 13:21:18

标签: c# system.reactive

[注意:如果重要,我使用的是3.1。另外,我在codereview上问了这个问题,但到目前为止还没有回复。]

我需要一个运算符来允许布尔流作为另一个流的门(当门流为真时让值传递,当它为假时丢弃它们)。我通常会使用Switch,但如果源流是冷的,它将继续重新创建它,这是我不想要的。

我也想在自己之后进行清理,以便在源或门完成时结果完成。

public static IObservable<T> When<T>(this IObservable<T> source, IObservable<bool> gate)
{
    var s = source.Publish().RefCount();
    var g = gate.Publish().RefCount();

    var sourceCompleted = s.TakeLast(1).DefaultIfEmpty().Select(_ => Unit.Default);
    var gateCompleted = g.TakeLast(1).DefaultIfEmpty().Select(_ => Unit.Default);

    var anyCompleted = Observable.Amb(sourceCompleted, gateCompleted);

    var flag = false;
    g.TakeUntil(anyCompleted).Subscribe(value => flag = value);

    return s.Where(_ => flag).TakeUntil(anyCompleted);
}

除了整体冗长之外,我不喜欢我订阅门,即使结果从未订阅(在这种情况下,此运算符应该是无操作)。有没有办法摆脱那个订阅?

我也试过这个实现,但是在自我清理后更糟糕的是:

return Observable.Create<T>(
    o =>
    {
        var flag = false;
        gate.Subscribe(value => flag = value);

        return source.Subscribe(
            value =>
            {
                if (flag) o.OnNext(value);
            });
    });

这些是我用来检查实现的测试:

[TestMethod]
public void TestMethod1()
{
    var output = new List<int>();

    var source = new Subject<int>();
    var gate = new Subject<bool>();

    var result = source.When(gate);
    result.Subscribe(output.Add, () => output.Add(-1));

    // the gate starts with false, so the source events are ignored
    source.OnNext(1);
    source.OnNext(2);
    source.OnNext(3);
    CollectionAssert.AreEqual(new int[0], output);

    // setting the gate to true will let the source events pass
    gate.OnNext(true);
    source.OnNext(4);
    CollectionAssert.AreEqual(new[] { 4 }, output);
    source.OnNext(5);
    CollectionAssert.AreEqual(new[] { 4, 5 }, output);

    // setting the gate to false stops source events from propagating again
    gate.OnNext(false);
    source.OnNext(6);
    source.OnNext(7);
    CollectionAssert.AreEqual(new[] { 4, 5 }, output);

    // completing the source also completes the result
    source.OnCompleted();
    CollectionAssert.AreEqual(new[] { 4, 5, -1 }, output);
}

[TestMethod]
public void TestMethod2()
{
    // completing the gate also completes the result
    var output = new List<int>();

    var source = new Subject<int>();
    var gate = new Subject<bool>();

    var result = source.When(gate);
    result.Subscribe(output.Add, () => output.Add(-1));

    gate.OnCompleted();
    CollectionAssert.AreEqual(new[] { -1 }, output);
}

3 个答案:

答案 0 :(得分:2)

更新:当门终止时终止。我在复制/粘贴中错过了TestMethod2

    return gate.Publish(_gate => source
        .WithLatestFrom(_gate.StartWith(false), (value, b) => (value, b))
        .Where(t => t.b)
        .Select(t => t.value)
        .TakeUntil(_gate.IgnoreElements().Materialize()
    ));

这会传递你的测试 TestMethod1,当门可观察时它不会终止。

public static IObservable<T> When<T>(this IObservable<T> source, IObservable<bool> gate)
{
    return source
        .WithLatestFrom(gate.StartWith(false), (value, b) => (value, b))
        .Where(t => t.b)
        .Select(t => t.value);
}

答案 1 :(得分:2)

这有效:

public static IObservable<T> When<T>(this IObservable<T> source, IObservable<bool> gate)
{
    return
        source.Publish(ss => gate.Publish(gs =>
            gs
                .Select(g => g ? ss : ss.IgnoreElements())
                .Switch()
                .TakeUntil(Observable.Amb(
                    ss.Select(s => true).Materialize().LastAsync(),
                    gs.Materialize().LastAsync()))));
}

这通过了两个测试。

答案 2 :(得分:1)

您与Observable.Create走在了正确的轨道上。您应该从observable上的两个订阅中调用onError和onCompleted,以便在需要时正确完成或错误。另外,如果您打算在IDisposableCreate完成之前处置When订阅,则通过返回source委托中的gate来确保两个订阅都已正确清理

    public static IObservable<T> When<T>(this IObservable<T> source, IObservable<bool> gate)
    {
        return Observable.Create<T>(
            o =>
            {
                var flag = false;
                var gs = gate.Subscribe(
                    value => flag = value,
                    e => o.OnError(e),
                    () => o.OnCompleted());

                var ss = source.Subscribe(
                    value =>
                    {
                        if (flag) o.OnNext(value);
                    },
                    e => o.OnError(e), 
                    () => o.OnCompleted());

                return new CompositeDisposable(gs, ss);
            });
    }

仅使用Rx运算符的更短但更难阅读的版本。对于冷可观测量,它可能需要为源提供发布/引用计数。

    public static IObservable<T> When<T>(this IObservable<T> source, IObservable<bool> gate)
    {
        return gate
            .Select(g => g ? source : source.IgnoreElements())
            .Switch()
            .TakeUntil(source.Materialize()
                             .Where(s => s.Kind == NotificationKind.OnCompleted));
    }