I would like feedback on this DistinctUntilChangedBy
operator for System.Reactive
that only emits when the current value is different than the last by a specified amount. Is there a better implementation?
I want to avoid multiple emits when the stream looks like this: 0.80, 0.81, 0.80, 0.81, etc.
Using the operator like this:
stream.DistinctUntilChangedBy(0.01).Subscribe(x => Console.WriteLine(x));
Should output this:
0.80
The operator looks like this and it is also on GitHub as a gist:
using System;
using System.Collections.Generic;
using System.Reactive.Linq;
namespace Gists.Reactive.Linq
{
public static partial class ObservableExtensions
{
///<summary>
///Only emit when the current value is different than the last by the specified amount.
///</summary>
public static IObservable<decimal> DistinctUntilChangedBy(this IObservable<decimal> source, decimal amount)
{
return source.DistinctUntilChanged(new DistinctUntilChangedByEqualityComparer(amount));
}
private class DistinctUntilChangedByEqualityComparer : IEqualityComparer<decimal>
{
private readonly decimal amount;
public DistinctUntilChangedByEqualityComparer(decimal amount)
{
this.amount = amount;
}
public bool Equals(decimal x, decimal y)
{
var diff = Math.Abs(x - y);
return diff <= Math.Abs(amount);
}
public int GetHashCode(decimal obj)
{
throw new NotSupportedException();
}
}
}
}