Pavel Ivchenkov
Pavel Ivchenkov

Reputation: 65

Rx .NET skip value changes by some scenario

I'm having trouble implementing a certain scenario with Rx. I have some code:

enum Status { NotConnected, Connecting, Connected }

class Provider
{
    public Status State { get => m_state; set => this.RaiseAndSetIfChanged(ref m_state, value); }
    public double Divergence { get => m_divergence; set => this.RaiseAndSetIfChanged(ref m_divergence, value); }
}

public void Run(Provider provider)
{
    provider.WhenAny(viewItem => viewItem.Divergence, change => change.Sender)
                                         .Throttle(TimeSpan.FromMilliseconds(500))
                                         .Subscribe(OnDivergenceChanged);
}

private void OnDivergenceChanged(Provider provider)
{
    ...
}

The status can be changed by the cyclogram NotConnected->Connecting->Connected.->NotConnected->Connecting...
Initial state is a NotConnected, the Divergence changes is not blocked.
I need to skip changing the Divergence value, starting from the moment of connection (state is Connecting) and ending 5 seconds after the "Connected" state is established.

Upvotes: 0

Views: 95

Answers (1)

NickL
NickL

Reputation: 1960

This is a possible solution:

IObservable<double> Divergence;
IObservable<Status> State;
IObservable<double> onDivergenceChanged = State
    .Select(state => state switch
    {
        Status.NotConnected => Divergence,
        Status.Connecting => Observable.Empty<double>(),
        Status.Connected => Observable.Timer(TimeSpan.FromSeconds(5)).Select(_ => Divergence).Switch(),
        _ => throw new ArgumentOutOfRangeException(nameof(state), state, null)
    })
    .Switch();

It's quite declarative - for each status, either take: a) the stream of numbers; b) nothing; c) the numbers after a 5 second timer.

Upvotes: 1

Related Questions