Skip to content

Commit

Permalink
Pairwise(not tested)
Browse files Browse the repository at this point in the history
  • Loading branch information
neuecc committed Jan 4, 2024
1 parent 27c5d39 commit 71b9e7f
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 2 deletions.
47 changes: 47 additions & 0 deletions src/R3/Operators/Pairwise.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
namespace R3;

public static partial class ObservableExtensions
{
public static Observable<(T Previous, T Current)> Pairwise<T>(this Observable<T> source)
{
return new Pairwise<T>(source);
}
}

internal sealed class Pairwise<T>(Observable<T> source) : Observable<(T Previous, T Current)>
{
protected override IDisposable SubscribeCore(Observer<(T Previous, T Current)> observer)
{
return source.Subscribe(new _Pairwise(observer));
}

sealed class _Pairwise(Observer<(T Previous, T Current)> observer) : Observer<T>
{
T? previous;
bool isFirst = true;

protected override void OnNextCore(T value)
{
if (isFirst)
{
isFirst = false;
previous = value;
return;
}

var pair = (previous!, value);
previous = value;
observer.OnNext(pair);
}

protected override void OnErrorResumeCore(Exception error)
{
observer.OnErrorResume(error);
}

protected override void OnCompletedCore(Result result)
{
observer.OnCompleted(result);
}
}
}
3 changes: 1 addition & 2 deletions src/R3/Operators/_Operators.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@ public static partial class ObservableExtensions
// TODO: this is working space, will remove this file after complete.

// Rx Merging:
// TODO:not-tested:CombineLatest, Zip, ZipLatest, WithLatestFrom, Switch
// , Pairwise
// TODO:not-tested:CombineLatest, Zip, ZipLatest, WithLatestFrom, Switch, Pairwise

// Standard Query:
// Distinct, DistinctBy, DistinctUntilChanged, Scan, DefaultIfEmpty
Expand Down

0 comments on commit 71b9e7f

Please sign in to comment.