使用Rx执行延迟采样的最佳方法是什么?

时间:2017-07-31 15:55:45

标签: c# system.reactive reactive-programming

我正在开发一个Xamarin应用,我已将Connectivity插件扩展为使用Rx而非事件。

我的目标是在重新建立连接时引入一点延迟,以便让网络适配器有时间连接到互联网(UWP的解决方法)。如果在此延迟中出现任何值,则只需要保留最后一个值,因为只有当前连接状态很重要。

这很好用,但感觉有点笨拙:

internal static class ConnectivityExtensions
{
    public static IObservable<bool> ToObservable(this IConnectivity @this)
    {
        var connectivity = Observable
            .FromEventPattern<ConnectivityChangedEventHandler, ConnectivityChangedEventArgs>(
                handler => @this.ConnectivityChanged += handler,
                handler => @this.ConnectivityChanged -= handler)
            .Select(args => args.EventArgs.IsConnected);

        var sampling = connectivity
            .Timestamp()
            .Select(ts => new
            {
                ts.Value,
                ts.Timestamp,
                // If reconnection, delay subscriber notification for 250ms
                DelayUntil = ts.Value ? (DateTimeOffset?)ts.Timestamp.Add(TimeSpan.FromMilliseconds(250)) : null
            })
            .Scan((acc, current) => new
            {
                current.Value,
                current.Timestamp,
                // If current notification is during reconnection notification delay period, delay the current notification too
                DelayUntil = current.Timestamp < acc.DelayUntil ? acc.DelayUntil : current.DelayUntil
            })
            // Perform reconnection delay
            .Delay(x => x.DelayUntil.HasValue
                ? Observable.Return(x.DelayUntil.Value).Delay(x.DelayUntil.Value)
                : Observable.Empty<DateTimeOffset>())
            // All delayed notifications are delayed until the same time, so we only need one notification to trigger sampling after delay
            .DistinctUntilChanged()
            .Select(_ => Unit.Default);

        return connectivity
            .Sample(sampling)
            .StartWith(@this.IsConnected)
            .DistinctUntilChanged()
            .Replay(1)
            .RefCount();
    }
}

示例输出:

通过这个例子,你可以看到我正在做的事情的好处。当“连接”改变时,延迟阻止订户处理数据,但是尚未建立互联网连接(UWP)。此外,这还可以保护用户免受任何快速“开/关”通知。

                                                                                     // StartsWith: True
ConnectivityChanged(null, new ConnectivityChangedEventArgs { IsConnected = true });  // Delay 250ms
Thread.Sleep(TimeSpan.FromMilliseconds(250));                                        // Sample: True, Ignored due to DistinctUntilChanged
ConnectivityChanged(null, new ConnectivityChangedEventArgs { IsConnected = false }); // Sample: False
Thread.Sleep(TimeSpan.FromMilliseconds(250));
ConnectivityChanged(null, new ConnectivityChangedEventArgs { IsConnected = true });  // Delay 250ms, Discarded due to Sample
ConnectivityChanged(null, new ConnectivityChangedEventArgs { IsConnected = false }); // Delayed by previous, Discarded due to Sample
ConnectivityChanged(null, new ConnectivityChangedEventArgs { IsConnected = true });  // Delayed by previous, Discarded due to Sample
ConnectivityChanged(null, new ConnectivityChangedEventArgs { IsConnected = false }); // Delayed by previous
Thread.Sleep(TimeSpan.FromMilliseconds(250));                                        // Sample: False, Ignored due to DistinctUntilChanged
ConnectivityChanged(null, new ConnectivityChangedEventArgs { IsConnected = true });  // Delay 250ms, Discarded due to Sample
ConnectivityChanged(null, new ConnectivityChangedEventArgs { IsConnected = false }); // Delayed by previous
Thread.Sleep(TimeSpan.FromMilliseconds(250));                                        // Sample: False, Ignored due to DistinctUntilChanged

// Final Output:
// True
// False

是否有更优化的方式来实现此类延迟采样?

2 个答案:

答案 0 :(得分:1)

如果我理解正确的话,这是一个大理石图,说明事情会如何发展:

T (millis)           : 0----250--500--1000-1250-1500-1750-2000
Connectivity         : ---F-------T---F----T-------F--T-------
ScanValueDelayUntil  : ---null----800-null-1500----null2100---
Sampling             : -------------x-----------x-----------x-
ResultSampled        : T------------T-----------T-----------T-
ResultSampledDistinct: T--------------------------------------

这似乎没有多大意义。你能描述一下你希望结果代表什么,或者纠正我错在哪里吗?

答案 1 :(得分:0)

在大约一年之后重新审视这个问题时,我发现了Throttle的无记录重载,这可以大大简化我想要做的事情。我还创建了自己的反应IConnectivity抽象来减少对特定库的依赖:

internal sealed class ReactiveCrossConnectivity : IConnectivity
{
    public IObservable<bool> IsConnected { get; }

    public ReactiveCrossConnectivity(
        Plugin.Connectivity.Abstractions.IConnectivity connectivity, 
        ISchedulerProvider scheduler)
    {
        IsConnected = Observable
            .FromEventPattern<ConnectivityChangedEventHandler, ConnectivityChangedEventArgs>(
                handler => connectivity.ConnectivityChanged += handler,
                handler => connectivity.ConnectivityChanged -= handler,
                scheduler.Defaults.ConstantTimeOperations)
            .Select(args => args.EventArgs.IsConnected)
            .Throttle(isConnected => isConnected
                ? Observable.Timer(TimeSpan.FromMilliseconds(250),
                      scheduler.Defaults.TimeBasedOperations)
                : Observable.Return<long>(0))
            .StartWith(scheduler.Defaults.ConstantTimeOperations, connectivity.IsConnected)
            .DistinctUntilChanged()
            .Replay(1, scheduler.Defaults.Iteration)
            .RefCount();
    }
}

这是确认行为的NUnit / NSubstitute测试:

public sealed class ReactiveCrossConnectivityTest : ReactiveTest
{
    [Test]
    public void IsConnected_ThrottlesOnConnect()
    {
        var connectivity = Substitute.For<Plugin.Connectivity.Abstractions.IConnectivity>();
        connectivity.IsConnected.Returns(true);
        var testScheduler = new TestScheduler();
        var sut = new ReactiveCrossConnectivity(
            connectivity, new SingleSchedulerProvider(testScheduler));
        var isConnectedObserver = testScheduler.CreateObserver<bool>();

        sut.IsConnected.Subscribe(isConnectedObserver);

        void Change(bool isConnected) => connectivity.ConnectivityChanged +=
            Raise.Event<ConnectivityChangedEventHandler>(connectivity,
                new ConnectivityChangedEventArgs { IsConnected = isConnected });

        testScheduler.Schedule(TimeSpan.FromTicks(3), () => Change(true));
        testScheduler.Schedule(TimeSpan.FromMilliseconds(251), () => Change(false));
        testScheduler.Schedule(TimeSpan.FromMilliseconds(501), () => Change(true));
        testScheduler.Schedule(TimeSpan.FromMilliseconds(751), () => Change(true));
        testScheduler.Schedule(TimeSpan.FromMilliseconds(752), () => Change(false));
        testScheduler.Schedule(TimeSpan.FromMilliseconds(753), () => Change(true));
        testScheduler.Schedule(TimeSpan.FromMilliseconds(754), () => Change(false));
        testScheduler.Schedule(TimeSpan.FromMilliseconds(1001), () => Change(true));
        testScheduler.Schedule(TimeSpan.FromMilliseconds(1002), () => Change(false));

        testScheduler.Start();

        isConnectedObserver.Messages.AssertEqual(
            OnNext(2, true),
            OnNext(TimeSpan.FromMilliseconds(251).Ticks + 1, false));
    }
}