Last active
December 8, 2019 12:06
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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