# R3 **Repository Path**: akwkevin/R3 ## Basic Information - **Project Name**: R3 - **Description**: No description available - **Primary Language**: Unknown - **License**: MIT - **Default Branch**: main - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2024-06-22 - **Last Updated**: 2024-06-22 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # R3 The new future of [dotnet/reactive](https://github.com/dotnet/reactive/) and [UniRx](https://github.com/neuecc/UniRx), which support many platforms including [Unity](#unity), [Godot](#godot), [Avalonia](#avalonia), [WPF](#wpf), [WinForms](#winforms), [WinUI3](#winui3), [Stride](#stride), [LogicLooper](#logiclooper), [MAUI](#maui), [MonoGame](#monogame), [Blazor](#blazor). I have over 10 years of experience with Rx, experience in implementing a custom Rx runtime ([UniRx](https://github.com/neuecc/UniRx)) for game engine, and experience in implementing an asynchronous runtime ([UniTask](https://github.com/Cysharp/UniTask/)) for game engine. Based on those experiences, I came to believe that there is a need to implement a new Reactive Extensions for .NET, one that reflects modern C# and returns to the core values of Rx. * Stopping the pipeline at OnError is a billion-dollar mistake. * IScheduler is the root of poor performance. * Frame-based operations, a missing feature in Rx, are especially important in game engines. * Single asynchronous operations should be entirely left to async/await. * Synchronous APIs should not be implemented. * Query syntax is a bad notation except for SQL. * The Necessity of a subscription list to prevent subscription leaks (similar to a Parallel Debugger) * Backpressure should be left to [IAsyncEnumerable](https://learn.microsoft.com/en-us/dotnet/csharp/asynchronous-programming/generate-consume-asynchronous-stream) and [Channels](https://devblogs.microsoft.com/dotnet/an-introduction-to-system-threading-channels/). * For distributed processing and queries, there are [GraphQL](https://graphql.org/), [Kubernetes](https://kubernetes.io/), [Orleans](https://learn.microsoft.com/en-us/dotnet/orleans/), [Akka.NET](https://getakka.net/), [gRPC](https://grpc.io/), [MagicOnion](https://github.com/Cysharp/MagicOnion). In other words, LINQ is not for EveryThing, and we believe that the essence of Rx lies in the processing of in-memory messaging (LINQ to Events), which will be our focus. We are not concerned with communication processes like [Reactive Streams](https://www.reactive-streams.org/). To address the shortcomings of dotnet/reactive, we have made changes to the core interfaces. In recent years, Rx-like frameworks optimized for language features, such as [Kotlin Flow](https://kotlinlang.org/docs/flow.html) and [Swift Combine](https://developer.apple.com/documentation/combine), have been standardized. C# has also evolved significantly, now at C# 12, and we believe there is a need for an Rx that aligns with the latest C#. Improving performance was also a theme in the reimplementation. For example, this is the result of the terrible performance of IScheduler and the performance difference caused by its removal. ![image](https://github.com/Cysharp/ZLogger/assets/46207/68a12664-a840-4725-a87c-8fdbb03b4a02) `Observable.Range(1, 10000).Subscribe()` You can also see interesting results in allocations with the addition and deletion to Subject. ![image](https://github.com/Cysharp/ZLogger/assets/46207/2194c086-37a3-44d6-8642-5fd0fa91b168) `x10000 subject.Subscribe() -> x10000 subscription.Dispose()` This is because dotnet/reactive has adopted ImmutableArray (or its equivalent) for Subject, which results in the allocation of a new array every time one is added or removed. Depending on the design of the application, a large number of subscriptions can occur (we have seen this especially in the complexity of games), which can be a critical issue. In R3, we have devised a way to achieve high performance while avoiding ImmutableArray. For those interested in learning more about the implementation philosophy and comparisons, please refer to my blog article [R3 — A New Modern Reimplementation of Reactive Extensions for C#](https://neuecc.medium.com/r3-a-new-modern-reimplementation-of-reactive-extensions-for-c-cf29abcc5826). Core Interface --- This library is distributed via NuGet, supporting .NET Standard 2.0, .NET Standard 2.1, .NET 6(.NET 7) and .NET 8 or above. > PM> Install-Package [R3](https://www.nuget.org/packages/R3) Some platforms(WPF, Avalonia, Unity, Godot) requires additional step to install. Please see [Platform Supports](#platform-supports) section in below. R3 code is mostly the same as standard Rx. Make the Observable via factory methods(Timer, Interval, FromEvent, Subject, etc...) and chain operator via LINQ methods. Therefore, your knowledge about Rx and documentation on Rx can be almost directly applied. If you are new to Rx, the [ReactiveX](https://reactivex.io/intro.html) website and [Introduction to Rx.NET](https://introtorx.com/) would be useful resources for reference. ```csharp using R3; var subscription = Observable.Interval(TimeSpan.FromSeconds(1)) .Select((_, i) => i) .Where(x => x % 2 == 0) .Subscribe(x => Console.WriteLine($"Interval:{x}")); var cts = new CancellationTokenSource(); _ = Task.Run(() => { Console.ReadLine(); cts.Cancel(); }); await Observable.Timer(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(3)) .TakeUntil(cts.Token) .ForEachAsync(x => Console.WriteLine($"Timer")); subscription.Dispose(); ``` The surface API remains the same as normal Rx, but the interfaces used internally are different and are not `IObservable/IObserver`. `IObservable` being the dual of `IEnumerable` is a beautiful definition, but it was not very practical in use. ```csharp public abstract class Observable { public IDisposable Subscribe(Observer observer); } public abstract class Observer : IDisposable { public void OnNext(T value); public void OnErrorResume(Exception error); public void OnCompleted(Result result); // Result is (Success | Failure) } ``` The biggest difference is that in normal Rx, when an exception occurs in the pipeline, it flows to `OnError` and the subscription is unsubscribed, but in R3, it flows to `OnErrorResume` and the subscription is not unsubscribed. I consider the automatic unsubscription by OnError to be a bad design for event handling. It's very difficult and risky to resolve it within an operator like Retry, and it also led to poor performance (there are many questions and complex answers about stopping and resubscribing all over the world). Also, converting OnErrorResume to OnError(OnCompleted(Result.Failure)) is easy and does not degrade performance, but the reverse is impossible. Therefore, the design was changed to not stop by default and give users the choice to stop. Since the original Rx contract was `OnError | OnCompleted`, it was changed to `OnCompleted(Result result)` to consolidate into one method. Result is a readonly struct with two states: `Success() | Failure(Exception)`. The reason for changing to an abstract class instead of an interface is that Rx has implicit complex contracts that interfaces do not guarantee. By making it an abstract class, we fully controlled the behavior of Subscribe, OnNext, and Dispose. This made it possible to manage the list of all subscriptions and prevent subscription leaks. ![image](https://github.com/Cysharp/ZLogger/assets/46207/149abca5-6d84-44ea-8373-b0e8cd2dc46a) Subscription leaks are a common problem in applications with long lifecycles, such as GUIs or games. Tracking all subscriptions makes it easy to prevent leaks. Internally, when subscribing, an Observer is always linked to the target Observable and doubles as a Subscription. This ensures that Observers are reliably connected from top to bottom, making tracking certain and clear that they are released on OnCompleted/Dispose. In terms of performance, because the Observer itself always becomes a Subscription, there is no need for unnecessary IDisposable allocations. TimeProvider instead of IScheduler --- In traditional Rx, `IScheduler` was used as an abstraction for time-based processing, but in R3, we have discontinued its use and instead opted for the [TimeProvider](https://learn.microsoft.com/en-us/dotnet/api/system.timeprovider?view=net-8.0) introduced in .NET 8. For example, the operators are defined as follows: ```csharp public static Observable Interval(TimeSpan period, TimeProvider timeProvider); public static Observable Delay(this Observable source, TimeSpan dueTime, TimeProvider timeProvider) public static Observable Debounce(this Observable source, TimeSpan timeSpan, TimeProvider timeProvider) // same as Throttle in dotnet/reactive ``` Originally, `IScheduler` had performance issues, and the internal implementation of dotnet/reactive was peppered with code that circumvented these issues using `PeriodicTimer` and `IStopwatch`, leading to unnecessary complexity. These can be better expressed with TimeProvider (`TimeProvider.CreateTimer()`, `TimeProvider.GetTimestamp()`). While TimeProvider is an abstraction for asynchronous operations, excluding the Fake for testing purposes, `IScheduler` included synchronous schedulers like `ImmediateScheduler` and `CurrentThreadScheduler`. However, these were also meaningless as applying them to time-based operators would cause blocking, and `CurrentThreadScheduler` had poor performance. ![image](https://github.com/Cysharp/ZLogger/assets/46207/68a12664-a840-4725-a87c-8fdbb03b4a02) `Observable.Range(1, 10000).Subscribe()` In R3, anything that requires synchronous execution (like Range) is treated as Immediate, and everything else is considered asynchronous and handled through TimeProvider. As for the implementation of TimeProvider, the standard TimeProvider.System using the ThreadPool is the default. For unit testing, FakeTimeProvider (Microsoft.Extensions.TimeProvider.Testing) is available. Additionally, many TimeProvider implementations are provided for different platforms, such as DispatcherTimerProvider for WPF and UpdateTimerProvider for Unity, enhancing ease of use tailored to each platform. Frame based operations --- In GUI applications, there's the message loop, and in game engines, there's the game loop. Platforms that operate based on loops are not uncommon. The idea of executing something after a few seconds or frames fits very well with Rx. Just as time has been abstracted through TimeProvider, we introduced a layer of abstraction for frames called FrameProvider, and added frame-based operators corresponding to all methods that accept TimeProvider. ```csharp public static Observable IntervalFrame(int periodFrame, FrameProvider frameProvider); public static Observable DelayFrame(this Observable source, int frameCount, FrameProvider frameProvider) public static Observable DebounceFrame(this Observable source, int frameCount, FrameProvider frameProvider) ``` The effectiveness of frame-based processing has been proven in Unity's Rx implementation, [neuecc/UniRx](https://github.com/neuecc/UniRx), which is one of the reasons why UniRx has gained strong support. There are also several operators unique to frame-based processing. ```csharp // push OnNext every frame. Observable.EveryUpdate().Subscribe(x => Console.WriteLine(x)); // take value until next frame eventSoure.TakeUntil(Observable.NextFrame()).Subscribe(); // polling value changed Observable.EveryValueChanged(this, x => x.Width).Subscribe(x => WidthText.Text = x.ToString()); Observable.EveryValueChanged(this, x => x.Height).Subscribe(x => HeightText.Text = x.ToString()); ``` `EveryValueChanged` could be interesting, as it converts properties without Push-based notifications like `INotifyPropertyChanged`. ![](https://cloud.githubusercontent.com/assets/46207/15827886/1573ff16-2c48-11e6-9876-4e4455d7eced.gif)` Subjects(ReactiveProperty) --- In R3, there are four types of Subjects: `Subject`, `ReactiveProperty`, `ReplaySubject`, and `ReplayFrameSubject`. `Subject` is an event in Rx. Just as an event can register multiple Actions and distribute values using Invoke, a `Subject` can register multiple `Observer`s and distribute values using OnNext, OnErrorResume, and OnCompleted. There are variations of Subject, such as `ReactiveProperty`, which holds a single value internally, `ReplaySubject`, which holds multiple values based on count or time, and `ReplayFrameSubject`, which holds multiple values based on frame time. The internally recorded values are distributed when Subscribe is called. `ReactiveProperty` corresponds to what would be a `BehaviorSubject`, but with the added functionality of eliminating duplicate values. Since you can choose to enable or disable duplicate elimination, it effectively becomes a superior alternative to `BehaviorSubject`, leading to the removal of `BehaviorSubject`. Here's an example of creating an observable model using `ReactiveProperty`: ```csharp // Reactive Notification Model public class Enemy { public ReactiveProperty CurrentHp { get; private set; } public ReactiveProperty IsDead { get; private set; } public Enemy(int initialHp) { // Declarative Property CurrentHp = new ReactiveProperty(initialHp); IsDead = CurrentHp.Select(x => x <= 0).ToReactiveProperty(); } } // --- // Click button, HP decrement MyButton.OnClickAsObservable().Subscribe(_ => enemy.CurrentHp.Value -= 99); // subscribe from notification model. enemy.CurrentHp.Subscribe(x => Console.WriteLine("HP:" + x)); enemy.IsDead.Where(isDead => isDead == true) .Subscribe(_ => { // when dead, disable button MyButton.SetDisable(); }); ``` In `ReactiveProperty`, the value is updated by `.Value` and if it is identical to the current value, no notification is issued. If you want to force notification of a value even if it is the same, call `.OnNext(value)`. `ReactiveProperty` has equivalents in other frameworks as well, such as [Android LiveData](https://developer.android.com/topic/libraries/architecture/livedata) and [Kotlin StateFlow](https://developer.android.com/kotlin/flow/stateflow-and-sharedflow), particularly effective for data binding in UI contexts. In .NET, there is a library called [runceel/ReactiveProperty](https://github.com/runceel/ReactiveProperty), which I originally created. Unlike dotnet/reactive's Subject, all Subjects in R3 (Subject, ReactiveProperty, ReplaySubject, ReplayFrameSubject) are designed to call OnCompleted upon disposal. This is because R3 is designed with a focus on subscription management and unsubscription. By calling OnCompleted, it ensures that all subscriptions are unsubscribed from the Subject, the upstream source of events, by default. If you wish to avoid calling OnCompleted, you can do so by calling `Dispose(false)`. `ReactiveProperty` is mutable, but it can be converted to a read-only `ReadOnlyReactiveProperty`. Following the [guidance for the Android UI Layer](https://developer.android.com/topic/architecture/ui-layer), the Kotlin code below is ```kotlin class NewsViewModel(...) : ViewModel() { private val _uiState = MutableStateFlow(NewsUiState()) val uiState: StateFlow = _uiState.asStateFlow() ... } ``` can be adapted to the following R3 code. ```csharp class NewsViewModel { ReactiveProperty _uiState = new(new NewsUiState()); public ReadOnlyReactiveProperty UiState => _uiState; } ``` In R3, we use a combination of a mutable private field and a readonly public property. By inheriting `ReactiveProperty` and overriding `OnValueChanging` and `OnValueChanged`, you can customize behavior, such as adding validation. ```csharp // Since the primary constructor sets values to fields before calling base, it is safe to call OnValueChanging in the base constructor. public sealed class ClampedReactiveProperty(T initialValue, T min, T max) : ReactiveProperty(initialValue) where T : IComparable { private static IComparer Comparer { get; } = Comparer.Default; protected override void OnValueChanging(ref T value) { if (Comparer.Compare(value, min) < 0) { value = min; } else if (Comparer.Compare(value, max) > 0) { value = max; } } } // For regular constructors, please set `callOnValueChangeInBaseConstructor` to false and manually call it once to correct the value. public sealed class ClampedReactiveProperty2 : ReactiveProperty where T : IComparable { private static IComparer Comparer { get; } = Comparer.Default; readonly T min, max; // callOnValueChangeInBaseConstructor to avoid OnValueChanging call before min, max set. public ClampedReactiveProperty2(T initialValue, T min, T max) : base(initialValue, EqualityComparer.Default, callOnValueChangeInBaseConstructor: false) { this.min = min; this.max = max; // modify currentValue manually OnValueChanging(ref GetValueRef()); } protected override void OnValueChanging(ref T value) { if (Comparer.Compare(value, min) < 0) { value = min; } else if (Comparer.Compare(value, max) > 0) { value = max; } } } ``` Additionally, `ReactiveProperty` supports serialization with `System.Text.JsonSerializer` in .NET 6 and above. For earlier versions, you need to implement `ReactivePropertyJsonConverterFactory` under the existing implementation and add it to the Converter. Disposable --- To bundle multiple IDisposables (Subscriptions), it's good to use Disposable's methods. In R3, depending on the performance, ```csharp Disposable.Combine(IDisposable d1, ..., IDisposable d8); Disposable.Combine(params IDisposable[]); Disposable.CreateBuilder(); CompositeDisposable DisposableBag ``` five types are available for use. In terms of performance advantages, the order is `Combine(d1,...,d8) (>= CreateBuilder) > Combine(IDisposable[]) >= CreateBuilder > DisposableBag > CompositeDisposable`. When the number of subscriptions is statically determined, Combine offers the best performance. Internally, for less than 8 arguments, it uses fields, and for 9 or more arguments, it uses an array, making Combine especially efficient for 8 arguments or less. ```csharp public partial class MainWindow : Window { IDisposable disposable; public MainWindow() { var d1 = Observable.IntervalFrame(1).Subscribe(); var d2 = Observable.IntervalFrame(1).Subscribe(); var d3 = Observable.IntervalFrame(1).Subscribe(); disposable = Disposable.Combine(d1, d2, d3); } protected override void OnClosed(EventArgs e) { disposable.Dispose(); } } ``` If there are many subscriptions and it's cumbersome to hold each one in a variable, `CreateBuilder` can be used instead. At build time, it combines according to the number of items added to it. Since the Builder itself is a struct, there are no allocations. ```csharp public partial class MainWindow : Window { IDisposable disposable; public MainWindow() { var d = Disposable.CreateBuilder(); Observable.IntervalFrame(1).Subscribe().AddTo(ref d); Observable.IntervalFrame(1).Subscribe().AddTo(ref d); Observable.IntervalFrame(1).Subscribe().AddTo(ref d); disposable = d.Build(); } protected override void OnClosed(EventArgs e) { disposable.Dispose(); } } ``` For dynamically added items, using `DisposableBag` is advisable. This is an add-only struct with only `Add/Clear/Dispose` methods. It can be used relatively quickly and with low allocation by holding it in a class field and passing it around by reference. However, it is not thread-safe. ```csharp public partial class MainWindow : Window { DisposableBag disposable; // DisposableBag is struct, no need new and don't copy public MainWindow() { Observable.IntervalFrame(1).Subscribe().AddTo(ref disposable); Observable.IntervalFrame(1).Subscribe().AddTo(ref disposable); Observable.IntervalFrame(1).Subscribe().AddTo(ref disposable); } void OnClick() { Observable.IntervalFrame(1).Subscribe().AddTo(ref disposable); } protected override void OnClosed(EventArgs e) { disposable.Dispose(); } } ``` `CompositeDisposable` is a class that also supports `Remove` and is thread-safe. It is the most feature-rich, but comparatively, it has the lowest performance. ```csharp public partial class MainWindow : Window { CompositeDisposable disposable = new CompositeDisposable(); public MainWindow() { Observable.IntervalFrame(1).Subscribe().AddTo(disposable); Observable.IntervalFrame(1).Subscribe().AddTo(disposable); Observable.IntervalFrame(1).Subscribe().AddTo(disposable); } void OnClick() { Observable.IntervalFrame(1).Subscribe().AddTo(disposable); } protected override void OnClosed(EventArgs e) { disposable.Dispose(); } } ``` Additionally, there are other utilities for Disposables as follows. ```csharp Disposable.Create(Action); Disposable.Dispose(...); SingleAssignmentDisposable SingleAssignmentDisposableCore // struct SerialDisposable SerialDisposableCore // struct ``` Subscription Management --- Managing subscriptions is one of the most crucial aspects of Rx, and inadequate management can lead to memory leaks. There are two patterns for unsubscribing in Rx. One is by disposing of the IDisposable (Subscription) returned by Subscribe. The other is by receiving OnCompleted. In R3, to enhance subscription cancellation on both fronts, it's now possible to bundle subscriptions using a variety of Disposable classes for Subscriptions, and for OnCompleted, the upstream side of events (such as Subject or Factory) has been made capable of emitting OnCompleted. Especially, Factories that receive a TimeProvider or FrameProvider can now take a CancellationToken. ```csharp public static Observable Interval(TimeSpan period, TimeProvider timeProvider, CancellationToken cancellationToken) public static Observable EveryUpdate(FrameProvider frameProvider, CancellationToken cancellationToken) ``` When cancelled, OnCompleted is sent, and all subscriptions are unsubscribed. ### ObservableTracker R3 incorporates a system called ObservableTracker. When activated, it allows you to view all subscription statuses. ```csharp ObservableTracker.EnableTracking = true; // default is false ObservableTracker.EnableStackTrace = true; using var d = Observable.Interval(TimeSpan.FromSeconds(1)) .Where(x => true) .Take(10000) .Subscribe(); // check subscription ObservableTracker.ForEachActiveTask(x => { Console.WriteLine(x); }); ``` ```csharp TrackingState { TrackingId = 1, FormattedType = Timer._Timer, AddTime = 2024/01/09 4:11:39, StackTrace =... } TrackingState { TrackingId = 2, FormattedType = Where`1._Where, AddTime = 2024/01/09 4:11:39, StackTrace =... } TrackingState { TrackingId = 3, FormattedType = Take`1._Take, AddTime = 2024/01/09 4:11:39, StackTrace =... } ``` Besides directly calling `ForEachActiveTask`, making it more accessible through a GUI can make it easier to check for subscription leaks. Currently, there is an integrated GUI for Unity, and there are plans to provide a screen using Blazor for other platforms. ObservableSystem, UnhandledExceptionHandler --- For time-based operators that do not specify a TimeProvider or FrameProvider, the default Provider of ObservableSystem is used. This is settable, so if there is a platform-specific Provider (for example, DispatcherTimeProvider in WPF), you can swap it out to create a more user-friendly environment. ```csharp public static class ObservableSystem { public static TimeProvider DefaultTimeProvider { get; set; } = TimeProvider.System; public static FrameProvider DefaultFrameProvider { get; set; } = new NotSupportedFrameProvider(); static Action unhandledException = DefaultUnhandledExceptionHandler; // Prevent +=, use Set and Get method. public static void RegisterUnhandledExceptionHandler(Action unhandledExceptionHandler) { unhandledException = unhandledExceptionHandler; } public static Action GetUnhandledExceptionHandler() { return unhandledException; } static void DefaultUnhandledExceptionHandler(Exception exception) { Console.WriteLine("R3 UnhandleException: " + exception.ToString()); } } ``` In CUI environments, by default, the FrameProvider will throw an exception. If you want to use FrameProvider in a CUI environment, you can set either `NewThreadSleepFrameProvider`, which sleeps in a new thread for a specified number of seconds, or `TimerFrameProvider`, which executes every specified number of seconds. ### UnhandledExceptionHandler When an exception passes through OnErrorResume and is not ultimately handled by Subscribe, the UnhandledExceptionHandler of ObservableSystem is called. This can be set with `RegisterUnhandledExceptionHandler`. By default, it writes to `Console.WriteLine`, but it may need to be changed to use `ILogger` or something else as required. Result Handling --- The `Result` received by OnCompleted has a field `Exception?`, where it's null in case of success and contains the Exception in case of failure. ```csharp // Typical processing code example void OnCompleted(Result result) { if (result.IsFailure) { // do failure _ = result.Exception; } else // result.IsSuccess { // do success } } ``` To generate a `Result`, in addition to using `Result.Success` and `Result.Failure(exception)`, Observer has OnCompleted() and OnCompleted(exception) as shortcuts for Success and Failure, respectively. ```csharp observer.OnCompleted(Result.Success); observer.OnCompleted(Result.Failure(exception)); observer.OnCompleted(); // same as Result.Success observer.OnCompleted(exception); // same as Result.Failure(exception) ``` Unit Testing --- For unit testing, you can use [FakeTimeProvider](https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.time.testing.faketimeprovider) of Microsoft.Extensions.TimeProvider.Testing. Additionally, in R3, there is a collection called LiveList, which allows you to obtain subscription statuses as a list. Combining these two features can be very useful for unit testing. ```csharp var fakeTime = new FakeTimeProvider(); var list = Observable.Timer(TimeSpan.FromSeconds(5), fakeTime).ToLiveList(); fakeTime.Advance(TimeSpan.FromSeconds(4)); list.AssertIsNotCompleted(); fakeTime.Advance(TimeSpan.FromSeconds(1)); list.AssertIsCompleted(); list.AssertEqual([Unit.Default]); ``` For FrameProvider, a `FakeFrameProvider` is provided as standard, and it can be used in the same way as `FakeTimeProvider`. ```csharp var cts = new CancellationTokenSource(); var frameProvider = new FakeFrameProvider(); var list = Observable.EveryUpdate(frameProvider, cts.Token) .Select(_ => frameProvider.GetFrameCount()) .ToLiveList(); list.AssertEqual([]); // list.Should().Equal(expected); frameProvider.Advance(); list.AssertEqual([0]); frameProvider.Advance(3); list.AssertEqual([0, 1, 2, 3]); cts.Cancel(); list.AssertIsCompleted(); // list.IsCompleted.Should().BeTrue(); frameProvider.Advance(); list.AssertEqual([0, 1, 2, 3]); list.AssertIsCompleted(); ``` Interoperability with `IObservable` --- `Observable` is not `IObservable`. You can convert both by these methods. * `public static Observable ToObservable(this IObservable source)` * `public static IObservable AsSystemObservable(this Observable source)` Interoperability with `async/await` --- R3 has special integration with `async/await`. First, all methods that return a single asynchronous operation have now become ***Async methods, returning `Task`. Furthermore, you can specify special behaviors when asynchronous methods are provided to Where/Select/Subscribe. | Name | ReturnType | | --- | --- | | **SelectAwait**(this `Observable` source, `Func>` selector, `AwaitOperation` awaitOperation = AwaitOperation.Sequential, `bool` configureAwait = true, `bool` cancelOnCompleted = true, `int` maxConcurrent = -1) | `Observable` | | **WhereAwait**(this `Observable` source, `Func>` predicate, `AwaitOperation` awaitOperation = AwaitOperation.Sequential, `bool` configureAwait = true, `bool` cancelOnCompleted = true, `int` maxConcurrent = -1) | `Observable` | | **SubscribeAwait**(this `Observable` source, `Func` onNextAsync, `AwaitOperation` awaitOperation = AwaitOperation.Sequential, `bool` configureAwait = true, `bool` cancelOnCompleted = true, `int` maxConcurrent = -1) | `IDisposable` | | **SubscribeAwait**(this `Observable` source, `Func` onNextAsync, `Action` onCompleted, `AwaitOperation` awaitOperation = AwaitOperation.Sequential, `bool` configureAwait = true, `bool` cancelOnCompleted = true, `int` maxConcurrent = -1) | `IDisposable` | | **SubscribeAwait**(this `Observable` source, `Func` onNextAsync, `Action` onErrorResume, `Action` onCompleted, `AwaitOperation` awaitOperation = AwaitOperation.Sequential, `bool` configureAwait = true, `bool` cancelOnCompleted = true, `int` maxConcurrent = -1) | `IDisposable` | ```csharp public enum AwaitOperation { /// All values are queued, and the next value waits for the completion of the asynchronous method. Sequential, /// Drop new value when async operation is running. Drop, /// If the previous asynchronous method is running, it is cancelled and the next asynchronous method is executed. Switch, /// All values are sent immediately to the asynchronous method. Parallel, /// All values are sent immediately to the asynchronous method, but the results are queued and passed to the next operator in order. SequentialParallel, /// Send the first value and the last value while the asynchronous method is running. ThrottleFirstLast } ``` ```csharp // for example... // Drop enables prevention of execution by multiple clicks button.OnClickAsObservable() .SelectAwait(async (_, ct) => { var req = await UnityWebRequest.Get("https://google.com/").SendWebRequest().WithCancellation(ct); return req.downloadHandler.text; }, AwaitOperation.Drop) .SubscribeToText(text); ``` `maxConcurrent` is only effective for `Parallel` and `SequentialParallel`, allowing control over the number of parallel operations. By default, it allows unlimited parallelization. `cancelOnCompleted` lets you choose whether to cancel the ongoing asynchronous method (by setting CancellationToken to Cancel) when the `OnCompleted` event is received. The default is true, meaning it will be cancelled. If set to false, it waits for the completion of the asynchronous method before calling the subsequent `OnCompleted` (potentially after issuing OnNext, depending on the case). Additionally, the following time-related filtering/aggregating methods can also accept asynchronous methods. | Name | ReturnType | | --- | --- | | **Debounce**(this `Observable` source, `Func` throttleDurationSelector, `Boolean` configureAwait = true) | `Observable` | | **ThrottleFirst**(this `Observable` source, `Func` sampler, `Boolean` configureAwait = true) | `Observable` | | **ThrottleLast**(this `Observable` source, `Func` sampler, `Boolean` configureAwait = true) | `Observable` | | **ThrottleFirstLast**(this `Observable` source, `Func` sampler, `Boolean` configureAwait = true) | `Observable` | | **SkipUntil**(this `Observable` source, `CancellationToken` cancellationToken) | `Observable` | | **SkipUntil**(this `Observable` source, `Task` task) | `Observable` | | **SkipUntil**(this `Observable` source, `Func` asyncFunc, `Boolean` configureAwait = true) | `Observable` | | **TakeUntil**(this `Observable` source, `CancellationToken` cancellationToken) | `Observable` | | **TakeUntil**(this `Observable` source, `Task` task) | `Observable` | | **TakeUntil**(this `Observable` source, `Func` asyncFunc, `Boolean` configureAwait = true) | `Observable` | | **Chunk**(this `Observable` source, `Func` asyncWindow, `Boolean` configureAwait = true) | `Observable` | For example, by using the asynchronous function version of Chunk, you can naturally and easily write complex processes such as generating chunks at random times instead of fixed times. ```csharp Observable.Interval(TimeSpan.FromSeconds(1)) .Index() .Chunk(async (_, ct) => { await Task.Delay(TimeSpan.FromSeconds(Random.Shared.Next(0, 5)), ct); }) .Subscribe(xs => { Console.WriteLine(string.Join(", ", xs)); }); ``` These asynchronous methods are immediately canceled when `OnCompleted` is issued, and the subsequent `OnCompleted` is executed. By utilizing async/await for Retry-related operations, you can achieve better handling. For instance, whereas the previous version of Rx could only retry the entire pipeline, with R3, which accepts async/await, it is possible to retry on a per asynchronous method execution basis. ```csharp button.OnClickAsObservable() .SelectAwait(async (_, ct) => { var retry = 0; AGAIN: try { var req = await UnityWebRequest.Get("https://google.com/").SendWebRequest().WithCancellation(ct); return req.downloadHandler.text; } catch { if (retry++ < 3) goto AGAIN; throw; } }, AwaitOperation.Drop) ``` Repeat can also be implemented in combination with async/await. In this case, handling complex conditions for Repeat might be easier than completing it with Rx alone. ```csharp while (!ct.IsCancellationRequested) { await button.OnClickAsObservable() .Take(1) .ForEachAsync(_ => { // do something }); } ``` Concurrency Policy --- The composition of operators is thread-safe, and it is expected that the values flowing through OnNext are on a single thread. In other words, if OnNext is issued on multiple threads, the operators may behave unexpectedly. This is the same as with dotnet/reactive. For example, while Subject itself is thread-safe, the operators are not thread-safe. ```csharp // dotnet/reactive var subject = new System.Reactive.Subjects.Subject(); // single execution shows 100 but actually 9* multiple times(broken) subject.Take(100).Count().Subscribe(x => Console.WriteLine(x)); Parallel.For(0, 1000, new ParallelOptions { MaxDegreeOfParallelism = 10 }, x => subject.OnNext(x)); ``` This means that the issuance of OnNext must always be done on a single thread. Also, ReactiveProperty, which corresponds to BehaviorSubject in dotnet/reactive, is not thread-safe itself, so updating the value (set Value or call OnNext) must always be done on a single thread. For converting external inputs into Observables, such as with FromEvent, and when the source of input issues in a multi-threaded manner, it is necessary to synchronize using `Synchronize` to construct the correct operator chain. Sampling Timing --- The `Sample(TimeSpan)` in dotnet/reactive starts a timer in the background when subscribed to, and uses that interval for filtering. Additionally, the timer continues to run in the background indefinitely. `ThrottleFirst/Last/FirstLast(TimeSpan)` in R3 behaves differently; the timer is stopped upon subscription and only starts when a value arrives. If the timer is stopped at that time, it starts, and then stops the timer after the specified duration. Also, overloads that accept an asynchronous function `Func`, such as `ThrottleFirst/Last/FirstLast`, `Chunk`, `SkipUntil`, `TakeUntil`), behave in such a way that if the asynchronous function is not running when a value arrives, the execution of the asynchronous function begins. This change is expected to result in consistent behavior across all operators. ObservableCollections --- As a special collection for monitoring changes in collections and handling them in R3, the [ObservableCollections](https://github.com/Cysharp/ObservableCollections)'s `ObservableCollections.R3` package is available. It has `ObservableList`, `ObservableDictionary`, `ObservableHashSet`, `ObservableQueue`, `ObservableStack`, `ObservableRingBuffer`, `ObservableFixedSizeRingBuffer` and these observe methods. ```csharp Observable> IObservableCollection.ObserveAdd() Observable> IObservableCollection.ObserveRemove() Observable> IObservableCollection.ObserveReplace() Observable> IObservableCollection.ObserveMove() Observable> IObservableCollection.ObserveReset() ``` XAML Platforms(`BindableReactiveProperty`) --- For XAML based application platforms, R3 provides `BindableReactiveProperty` that can bind observable property to view like [Android LiveData](https://developer.android.com/topic/libraries/architecture/livedata) and [Kotlin StateFlow](https://developer.android.com/kotlin/flow/.stateflow-and-sharedflow). It implements [INotifyPropertyChanged](https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.inotifypropertychanged) and [INotifyDataErrorInfo](https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.inotifydataerrorinfo). Simple usage, expose `BindableReactiveProperty` via `new` or `ToBindableReactiveProperty`. Here is the simple In and Out BindableReactiveProperty ViewModel, Xaml and code-behind. In xaml, `.Value` to bind property. ```csharp public class BasicUsagesViewModel : IDisposable { public BindableReactiveProperty Input { get; } public BindableReactiveProperty Output { get; } public BasicUsagesViewModel() { Input = new BindableReactiveProperty(""); Output = Input.Select(x => x.ToUpper()).ToBindableReactiveProperty(""); } public void Dispose() { Disposable.Dispose(Input, Output); } } ``` ```xml ``` ```csharp namespace WpfApp1; public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } protected override void OnClosed(EventArgs e) { (this.DataContext as IDisposable)?.Dispose(); } } ``` ![image](https://github.com/Cysharp/R3/assets/46207/01c3738f-e941-412e-b517-8e7867d6f709) BindableReactiveProperty also supports validation via DataAnnotation or custom logic. If you want to use DataAnnotation attribute, require to call `EnableValidation()` in field initializer or `EnableValidation(Expression selfSelector)` in constructor. ```csharp public class ValidationViewModel : IDisposable { // Pattern 1. use EnableValidation to enable DataAnnotation validation in field initializer [Range(0.0, 300.0)] public BindableReactiveProperty Height { get; } = new BindableReactiveProperty().EnableValidation(); [Range(0.0, 300.0)] public BindableReactiveProperty Weight { get; } IDisposable customValidation1Subscription; public BindableReactiveProperty CustomValidation1 { get; set; } public BindableReactiveProperty CustomValidation2 { get; set; } public ValidationViewModel() { // Pattern 2. use EnableValidation(Expression) to enable DataAnnotation validation Weight = new BindableReactiveProperty().EnableValidation(() => Weight); // Pattern 3. EnableValidation() and call OnErrorResume to set custom error meessage CustomValidation1 = new BindableReactiveProperty().EnableValidation(); customValidation1Subscription = CustomValidation1.Subscribe(x => { if (0.0 <= x && x <= 300.0) return; CustomValidation1.OnErrorResume(new Exception("value is not in range.")); }); // Pattern 4. simplified version of Pattern3, EnableValidation(Func) CustomValidation2 = new BindableReactiveProperty().EnableValidation(x => { if (0.0 <= x && x <= 300.0) return null; // null is no validate result return new Exception("value is not in range."); }); } public void Dispose() { Disposable.Dispose(Height, Weight, CustomValidation1, customValidation1Subscription, CustomValidation2); } } ``` ```xml ``` ![image](https://github.com/Cysharp/R3/assets/46207/f80149e6-1573-46b5-9a77-b78776dd3527) ### ReactiveCommand `ReactiveCommand` is observable [ICommand](https://learn.microsoft.com/en-us/dotnet/api/system.windows.input.icommand) implementation. It can create from `Observable canExecuteSource`. ```csharp public class CommandViewModel : IDisposable { public BindableReactiveProperty OnCheck { get; } // bind to CheckBox public ReactiveCommand ShowMessageBox { get; } // bind to Button public CommandViewModel() { OnCheck = new BindableReactiveProperty(); ShowMessageBox = OnCheck.ToReactiveCommand(_ => { MessageBox.Show("clicked"); }); } public void Dispose() { Disposable.Dispose(OnCheck, ShowMessageBox); } } ``` ```xml