Skip to content

Instantly share code, notes, and snippets.

@mgnslndh
Last active December 8, 2019 12:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mgnslndh/a8ec564faf19c1c4ade44be1a32c3679 to your computer and use it in GitHub Desktop.
Save mgnslndh/a8ec564faf19c1c4ade44be1a32c3679 to your computer and use it in GitHub Desktop.
Only emit when the current value is different than the last by the specified amount.
using System;
using System.Collections.Generic;
using System.Reactive.Linq;
namespace Gists.Reactive.Linq
{
public static partial class ObservableExtensions
{
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();
}
}
}
}
using System;
using System.Collections.Generic;
using System.Reactive.Linq;
namespace Gists.Reactive.Linq
{
// https://reactivex.slack.com/archives/C02B9R3QA/p1575655074122700
public static partial class ObservableExtensions
{
public static IObservable<decimal> DistinctUntilChangedBy(this IObservable<decimal> source, decimal amount)
{
return source
.Scan(Tuple.Create(0m, 0m), (acc, current) => Tuple.Create(acc.Item2, current))
.Where(t => Math.Abs(t.Item2 - t.Item1) >= Math.Abs(amount))
.Select(t => t.Item2);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment