R3Extensions.WinUI3 1.3.1

dotnet add package R3Extensions.WinUI3 --version 1.3.1
                    
NuGet\Install-Package R3Extensions.WinUI3 -Version 1.3.1
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="R3Extensions.WinUI3" Version="1.3.1" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="R3Extensions.WinUI3" Version="1.3.1" />
                    
Directory.Packages.props
<PackageReference Include="R3Extensions.WinUI3" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add R3Extensions.WinUI3 --version 1.3.1
                    
#r "nuget: R3Extensions.WinUI3, 1.3.1"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package R3Extensions.WinUI3@1.3.1
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=R3Extensions.WinUI3&version=1.3.1
                    
Install as a Cake Addin
#tool nuget:?package=R3Extensions.WinUI3&version=1.3.1
                    
Install as a Cake Tool

R3

The new future of dotnet/reactive and UniRx, which support many platforms including Unity, Godot, Avalonia, WPF, WinForms, WinUI3, Stride, LogicLooper, MAUI, MonoGame, Blazor, Uno.

I have over 10 years of experience with Rx, experience in implementing a custom Rx runtime (UniRx) for game engine, and experience in implementing an asynchronous runtime (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 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 and Channels.
  • For distributed processing and queries, there are GraphQL, Kubernetes, Orleans, Akka.NET, gRPC, 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.

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 and Swift 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 Observable.Range(1, 10000).Subscribe()

You can also see interesting results in allocations with the addition and deletion to Subject.

image 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#.

Core Interface

This library is distributed via NuGet packages/R3, supporting .NET Standard 2.0, .NET Standard 2.1, .NET 6(.NET 7) and .NET 8 or above.

dotnet add package R3

Some platforms(WPF, Avalonia, Unity, Godot, etc...) requires additional step to install. Please see 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 website and Introduction to Rx.NET would be useful resources for reference.

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<T>/IObserver<T>.

IObservable<T> being the dual of IEnumerable<T> is a beautiful definition, but it was not very practical in use.

public abstract class Observable<T>
{
    public IDisposable Subscribe(Observer<T> observer);
}

public abstract class Observer<T> : 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

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 introduced in .NET 8. For example, the operators are defined as follows:

public static Observable<Unit> Interval(TimeSpan period, TimeProvider timeProvider);
public static Observable<T> Delay<T>(this Observable<T> source, TimeSpan dueTime, TimeProvider timeProvider)
public static Observable<T> Debounce<T>(this Observable<T> 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 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 DispatcherTimeProvider for WPF and UpdateTimeProvider 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.

public static Observable<Unit> IntervalFrame(int periodFrame, FrameProvider frameProvider);
public static Observable<T> DelayFrame<T>(this Observable<T> source, int frameCount, FrameProvider frameProvider)
public static Observable<T> DebounceFrame<T>(this Observable<T> source, int frameCount, FrameProvider frameProvider)

The effectiveness of frame-based processing has been proven in Unity's Rx implementation, neuecc/UniRx, which is one of the reasons why UniRx has gained strong support.

There are also several operators unique to frame-based processing.

// 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.

alternate text is missing from this package README image`

Subjects(ReactiveProperty)

In R3, there are five types of Subjects: Subject, BehaviorSubject, 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 Observers and distribute values using OnNext, OnErrorResume, and OnCompleted. There are variations of Subject, such as BehaviorSubject and 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. In addition, since the value can be set with .Value, it can be utilized for binding on XAML platforms, etc.

Here's an example of creating an observable model using ReactiveProperty:

// Reactive Notification Model
public class Enemy
{
    public ReactiveProperty<long> CurrentHp { get; private set; }

    public ReactiveProperty<bool> IsDead { get; private set; }

    public Enemy(int initialHp)
    {
        // Declarative Property
        CurrentHp = new ReactiveProperty<long>(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 and Kotlin StateFlow, particularly effective for data binding in UI contexts. In .NET, there is a library called runceel/ReactiveProperty, which I originally created.

Unlike dotnet/reactive's Subject, all Subjects in R3 (Subject, BehaviorSubject, 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, the Kotlin code below is

class NewsViewModel(...) : ViewModel() {

    private val _uiState = MutableStateFlow(NewsUiState())
    val uiState: StateFlow<NewsUiState> = _uiState.asStateFlow()
    ...
}

can be adapted to the following R3 code.

class NewsViewModel
{
    ReactiveProperty<NewsUiState> _uiState = new(new NewsUiState());
    public ReadOnlyReactiveProperty<NewsUiState> 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.

// 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>(T initialValue, T min, T max)
    : ReactiveProperty<T>(initialValue) where T : IComparable<T>
{
    private static IComparer<T> Comparer { get; } = Comparer<T>.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<T>
    : ReactiveProperty<T> where T : IComparable<T>
{
    private static IComparer<T> Comparer { get; } = Comparer<T>.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<T>.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.

As an internal implementation, Subject and ReactiveProperty has a lightweight implementation that consumes less memory. However, in exchange, its behavior differs slightly, especially in multi-threaded environments. For precautions related to multi-threading, please refer to the Concurrency Policy section.

Disposable

To bundle multiple IDisposables (Subscriptions), it's good to use Disposable's methods. In R3, depending on the performance,

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.

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.

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.

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.

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.

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.

public static Observable<Unit> Interval(TimeSpan period, TimeProvider timeProvider, CancellationToken cancellationToken)
public static Observable<Unit> 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.

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);
});
TrackingState { TrackingId = 1, FormattedType = Timer._Timer, AddTime = 2024/01/09 4:11:39, StackTrace =... }
TrackingState { TrackingId = 2, FormattedType = Where`1._Where<Unit>, AddTime = 2024/01/09 4:11:39, StackTrace =... }
TrackingState { TrackingId = 3, FormattedType = Take`1._Take<Unit>, 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.

public static class ObservableSystem
{
    public static TimeProvider DefaultTimeProvider { get; set; } = TimeProvider.System;
    public static FrameProvider DefaultFrameProvider { get; set; } = new NotSupportedFrameProvider();

    static Action<Exception> unhandledException = DefaultUnhandledExceptionHandler;

    // Prevent +=, use Set and Get method.
    public static void RegisterUnhandledExceptionHandler(Action<Exception> unhandledExceptionHandler)
    {
        unhandledException = unhandledExceptionHandler;
    }

    public static Action<Exception> GetUnhandledExceptionHandler()
    {
        return unhandledException;
    }

    static void DefaultUnhandledExceptionHandler(Exception exception)
    {
        Console.WriteLine("R3 UnhandledException: " + 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.

// 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.

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 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.

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.

var cts = new CancellationTokenSource();
var frameProvider = new FakeFrameProvider();

var list = Observable.EveryUpdate(frameProvider, cts.Token)
    .Select(_ => frameProvider.GetFrameCount())
    .ToLiveList();

list.AssertEqual([]); // list.ShouldBe(expected);

frameProvider.Advance();
list.AssertEqual([0]);

frameProvider.Advance(3);
list.AssertEqual([0, 1, 2, 3]);

cts.Cancel();
list.AssertIsCompleted(); // list.IsCompleted.ShouldBeTrue();

frameProvider.Advance();
list.AssertEqual([0, 1, 2, 3]);
list.AssertIsCompleted();

AssertEqual is a test helper. You can create your own helper to use with the test library.

public static class LiveListExtensions
{
    // Shouldbe() is xUnit + Shouldly
    public static void AssertEqual<T>(this LiveList<T> list, params T[] expected)
    {
        list.ShouldBe(expected);
    }

    public static void AssertEqual<T>(this LiveList<T[]> list, params T[][] expected)
    {
        list.Count.ShouldBe(expected.Length);

        for (int i = 0; i < expected.Length; i++)
        {
            list[i].ShouldBe(expected[i]);
        }
    }

    public static void AssertEmpty<T>(this LiveList<T> list)
    {
        list.Count.ShouldBe(0);
    }

    public static void AssertIsCompleted<T>(this LiveList<T> list)
    {
        list.IsCompleted.ShouldBeTrue();
    }

    public static void AssertIsNotCompleted<T>(this LiveList<T> list)
    {
        list.IsCompleted.ShouldBeFalse();
    }

    public static void Advance(this FakeTimeProvider timeProvider, int seconds)
    {
        timeProvider.Advance(TimeSpan.FromSeconds(seconds));
    }
}

Interoperability with IObservable<T>

Observable<T> is not IObservable<T>. You can convert both by these methods.

  • public static Observable<T> ToObservable<T>(this IObservable<T> source)
  • public static IObservable<T> AsSystemObservable<T>(this Observable<T> 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<T>.

Methods that convert to such Task (for example FirstAsync, LastAsync) transform OnErrorResume's Exception into a Faulted Task, similar to OnCompleted(Exception). Note that since the Catch operator does not capture OnErrorResume, if you want integrated error handling, please use OnErrorResumeAsFailure() to convert OnErrorResume(Exception) to OnCompleted(Exception).

Furthermore, you can specify special behaviors when asynchronous methods are provided to Where/Select/Subscribe.

Name ReturnType
SelectAwait(this Observable<T> source, Func<T, CancellationToken, ValueTask<TResult>> selector, AwaitOperation awaitOperation = AwaitOperation.Sequential, bool configureAwait = true, bool cancelOnCompleted = true, int maxConcurrent = -1) Observable<TResult>
WhereAwait(this Observable<T> source, Func<T, CancellationToken, ValueTask<Boolean>> predicate, AwaitOperation awaitOperation = AwaitOperation.Sequential, bool configureAwait = true, bool cancelOnCompleted = true, int maxConcurrent = -1) Observable<T>
SubscribeAwait(this Observable<T> source, Func<T, CancellationToken, ValueTask> onNextAsync, AwaitOperation awaitOperation = AwaitOperation.Sequential, bool configureAwait = true, bool cancelOnCompleted = true, int maxConcurrent = -1) IDisposable
SubscribeAwait(this Observable<T> source, Func<T, CancellationToken, ValueTask> onNextAsync, Action<Result> onCompleted, AwaitOperation awaitOperation = AwaitOperation.Sequential, bool configureAwait = true, bool cancelOnCompleted = true, int maxConcurrent = -1) IDisposable
SubscribeAwait(this Observable<T> source, Func<T, CancellationToken, ValueTask> onNextAsync, Action<Exception> onErrorResume, Action<Result> onCompleted, AwaitOperation awaitOperation = AwaitOperation.Sequential, bool configureAwait = true, bool cancelOnCompleted = true, int maxConcurrent = -1) IDisposable
public enum AwaitOperation
{
    /// <summary>All values are queued, and the next value waits for the completion of the asynchronous method.</summary>
    Sequential,
    /// <summary>Drop new value when async operation is running.</summary>
    Drop,
    /// <summary>If the previous asynchronous method is running, it is cancelled and the next asynchronous method is executed.</summary>
    Switch,
    /// <summary>All values are sent immediately to the asynchronous method.</summary>
    Parallel,
    /// <summary>All values are sent immediately to the asynchronous method, but the results are queued and passed to the next operator in order.</summary>
    SequentialParallel,
    /// <summary>Send the first value and the last value while the asynchronous method is running.</summary>
    ThrottleFirstLast
}
// 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<T> source, Func<T, CancellationToken, ValueTask> throttleDurationSelector, Boolean configureAwait = true) Observable<T>
ThrottleFirst(this Observable<T> source, Func<T, CancellationToken, ValueTask> sampler, Boolean configureAwait = true) Observable<T>
ThrottleLast(this Observable<T> source, Func<T, CancellationToken, ValueTask> sampler, Boolean configureAwait = true) Observable<T>
ThrottleFirstLast(this Observable<T> source, Func<T, CancellationToken, ValueTask> sampler, Boolean configureAwait = true) Observable<T>
SkipUntil(this Observable<T> source, CancellationToken cancellationToken) Observable<T>
SkipUntil(this Observable<T> source, Task task) Observable<T>
SkipUntil(this Observable<T> source, Func<T, CancellationToken, ValueTask> asyncFunc, Boolean configureAwait = true) Observable<T>
TakeUntil(this Observable<T> source, CancellationToken cancellationToken) Observable<T>
TakeUntil(this Observable<T> source, Task task) Observable<T>
TakeUntil(this Observable<T> source, Func<T, CancellationToken, ValueTask> asyncFunc, Boolean configureAwait = true) Observable<T>
Chunk(this Observable<T> source, Func<T, CancellationToken, ValueTask> asyncWindow, Boolean configureAwait = true) Observable<T[]>

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.

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.

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.

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.

// dotnet/reactive
var subject = new System.Reactive.Subjects.Subject<int>();

// 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. 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.

subject.Synchronize(gate).Take(100).Count().Subscribe();

Unlike dotnet/reactive, R3.Subject.OnNext is not ThreadSafe. If you are calling OnNext from multiple threads, please use a lock.

In R3, ReplaySubject and BehaviorSubject do not require Synchronize and are thread-safe, including OnNext.

ReactiveProperty is not thread-safe and OnNext, set Value and Subscribe cannot be called simultaneously. If you need to use it in such a situation, use SynchronizedReactiveProperty instead.

class MyClass
{
    public SynchronizedReactiveProperty<int> Prop { get; } = new();
}

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<T, CancellationToken, ValueTask>, 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's ObservableCollections.R3 package is available.

It has ObservableList<T>, ObservableDictionary<TKey, TValue>, ObservableHashSet<T>, ObservableQueue<T>, ObservableStack<T>, ObservableRingBuffer<T>, ObservableFixedSizeRingBuffer<T> and these observe methods.

Observable<CollectionAddEvent<T>> IObservableCollection<T>.ObserveAdd()
Observable<CollectionRemoveEvent<T>> IObservableCollection<T>.ObserveRemove()
Observable<CollectionReplaceEvent<T>> IObservableCollection<T>.ObserveReplace()
Observable<CollectionMoveEvent<T>> IObservableCollection<T>.ObserveMove()
Observable<CollectionResetEvent<T>> IObservableCollection<T>.ObserveReset()

XAML Platforms(BindableReactiveProperty<T>)

For XAML based application platforms, R3 provides BindableReactiveProperty<T> that can bind observable property to view like Android LiveData and Kotlin StateFlow. It implements INotifyPropertyChanged and INotifyDataErrorInfo.

Simple usage, expose BindableReactiveProperty<T> via new or ToBindableReactiveProperty.

Here is the simple In and Out BindableReactiveProperty ViewModel, Xaml and code-behind. In xaml, .Value to bind property.

public class BasicUsagesViewModel : IDisposable
{
    public BindableReactiveProperty<string> Input { get; }
    public BindableReactiveProperty<string> Output { get; }

    public BasicUsagesViewModel()
    {
        Input = new BindableReactiveProperty<string>("");
        Output = Input.Select(x => x.ToUpper()).ToBindableReactiveProperty("");
    }

    public void Dispose()
    {
        Disposable.Dispose(Input, Output);
    }
}
<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp1"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Window.DataContext>
        <local:BasicUsagesViewModel />
    </Window.DataContext>
    <StackPanel>
        <TextBlock Text="Basic usages" FontSize="24" />

        <Label Content="Input" />
        <TextBox Text="{Binding Input.Value, UpdateSourceTrigger=PropertyChanged}" />

        <Label Content="Output" />
        <TextBlock Text="{Binding Output.Value}" />
    </StackPanel>
</Window>
namespace WpfApp1;

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    protected override void OnClosed(EventArgs e)
    {
        (this.DataContext as IDisposable)?.Dispose();
    }
}

image

BindableReactiveProperty also supports validation via DataAnnotation or custom logic. If you want to use DataAnnotation attribute, require to call EnableValidation<T>() in field initializer or EnableValidation(Expression selfSelector) in constructor.

public class ValidationViewModel : IDisposable
{
    // Pattern 1. use EnableValidation<T> to enable DataAnnotation validation in field initializer
    [Range(0.0, 300.0)]
    public BindableReactiveProperty<double> Height { get; } = new BindableReactiveProperty<double>().EnableValidation<ValidationViewModel>();

    [Range(0.0, 300.0)]
    public BindableReactiveProperty<double> Weight { get; }

    IDisposable customValidation1Subscription;
    public BindableReactiveProperty<double> CustomValidation1 { get; set; }

    public BindableReactiveProperty<double> CustomValidation2 { get; set; }

    public ValidationViewModel()
    {
        // Pattern 2. use EnableValidation(Expression) to enable DataAnnotation validation
        Weight = new BindableReactiveProperty<double>().EnableValidation(() => Weight);

        // Pattern 3. EnableValidation() and call OnErrorResume to set custom error message
        CustomValidation1 = new BindableReactiveProperty<double>().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<T, Exception?>)
        CustomValidation2 = new BindableReactiveProperty<double>().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);
    }
}
<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp1"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Window.DataContext>
        <local:ValidationViewModel />
    </Window.DataContext>

    <StackPanel Margin="10">
        <Label Content="Validation" />
        <TextBox Text="{Binding Height.Value, UpdateSourceTrigger=PropertyChanged}"  />
        <TextBox  Text="{Binding Weight.Value, UpdateSourceTrigger=PropertyChanged}" />
        <TextBox  Text="{Binding CustomValidation1.Value, UpdateSourceTrigger=PropertyChanged}" />
        <TextBox  Text="{Binding CustomValidation2.Value, UpdateSourceTrigger=PropertyChanged}" />
    </StackPanel>
</Window>

image

Validation using EnableValidation does not trigger for initial values by default. This means that even if you don't allow empty strings, the validation error won't appear for an initially empty value. If you want to perform validation on initial values, you can call ForceValidate() after EnableValidation.

Weight = new BindableReactiveProperty<double>()
    .EnableValidation(() => Weight)
    .ForceValidate();

There is also IReadOnlyBindableReactiveProperty<T>, which is preferable when ReadOnly is required in binding, can create from IObservable<T>.ToReadOnlyBindableReactiveProperty<T>.

ReactiveCommand

ReactiveCommand<T> and ReactiveCommand are observable ICommand implementation. It can create from Observable<bool> canExecuteSource.

public class CommandViewModel : IDisposable
{
    public BindableReactiveProperty<bool> OnCheck { get; } // bind to CheckBox
    public ReactiveCommand ShowMessageBox { get; }   // bind to Button, non generics ReactiveCommand is ReactiveCommand<Unit>

    public CommandViewModel()
    {
        OnCheck = new BindableReactiveProperty<bool>();
        ShowMessageBox = OnCheck.ToReactiveCommand(_ =>
        {
            MessageBox.Show("clicked");
        });
    }

    public void Dispose()
    {
        Disposable.Dispose(OnCheck, ShowMessageBox);
    }
}
<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp1"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Window.DataContext>
        <local:CommandViewModel />
    </Window.DataContext>
    <StackPanel Margin="10">
        <Label Content="Command" />
        <CheckBox IsChecked="{Binding OnCheck.Value}" />
        <Button Content="Btn" Command="{Binding ShowMessageBox}" />
    </StackPanel>
</Window>

rpcommand

INotifyPropertyChanged to Observable

To convert properties of INotifyPropertyChanged and INotifyPropertyChanging into Observables, you can use ObservePropertyChanged and ObservePropertyChanging.

var person = new Person { Name = "foo" };

person.ObservePropertyChanged(x => x.Name)
      .Subscribe(x => Console.WriteLine($"Changed:{x}"));

p.Name = "bar";
p.Name = "baz";

Func<T, TProperty> propertySelector only supports simple property name lambda. This is because, in R3, CallerArgumentExpression is used to extract, for example from x => x.Name to "Name".

FromEvent

To convert existing events into Observables, use FromEvent. Because it requires the conversion of delegates and has a unique way of calling, please refer to the following sample.

Observable.FromEvent<RoutedEventHandler, RoutedEventArgs>(
    h => (sender, e) => h(e),
    e => button.Click += e,
    e => button.Click -= e);

Platform Supports

Even without adding specific platform support, it is possible to use only the core library. However, Rx becomes more user-friendly by replacing the standard TimeProvider and FrameProvider with those optimized for each platform. For example, while the standard TimeProvider is thread-based, using a UI thread-based TimeProvider for each platform can eliminate the need for dispatch through ObserveOn, enhancing usability. Additionally, since message loops differ across platforms, the use of individual FrameProvider is essential.

Although standard support is provided for the following platforms, by implementing TimeProvider and FrameProvider, it is possible to support any environment, including in-house game engine or other frameworks.

WPF

PM> Install-Package R3Extensions.WPF

R3Extensions.WPF package has two providers.

  • WpfDispatcherTimeProvider
  • WpfRenderingFrameProvider

Calling WpfProviderInitializer.SetDefaultObservableSystem() at startup will replace ObservableSystem.DefaultTimeProvider and ObservableSystem.DefaultFrameProvider with the aforementioned providers.

public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
        // You need to set UnhandledExceptionHandler
        WpfProviderInitializer.SetDefaultObservableSystem(ex => Trace.WriteLine($"R3 UnhandledException:{ex}"));
    }
}

As a result, time based operations are replaced with DispatcherTimer, allowing you to reflect time based operations on the UI without having to use ObserveOn.

WpfRenderingFrameProvider is a frame-based loop system synchronized with the CompositionTarget.Rendering event. This allows for writing code that, for example, reads and reflects changes in values that do not implement INotifyPropertyChanged.

public partial class MainWindow : Window
{
    IDisposable disposable;

    public MainWindow()
    {
        InitializeComponent();

        var d1 = Observable.EveryValueChanged(this, x => x.Width).Subscribe(x => WidthText.Text = x.ToString());
        var d2 = Observable.EveryValueChanged(this, x => x.Height).Subscribe(x => HeightText.Text = x.ToString());

        disposable = Disposable.Combine(d1, d2);
    }

    protected override void OnClosed(EventArgs e)
    {
        disposable.Dispose();
    }
}

alternate text is missing from this package README image

In addition to the above, the following ObserveOn/SubscribeOn methods have been added.

  • ObserveOnDispatcher
  • ObserveOnCurrentDispatcher
  • SubscribeOnDispatcher
  • SubscribeOnCurrentDispatcher

ViewModel binding support, see BindableReactiveProperty<T> section.

Avalonia

PM> Install-Package R3Extensions.Avalonia

R3Extensions.Avalonia package has these providers.

  • AvaloniaDispatcherTimeProvider
  • AvaloniaDispatcherFrameProvider
  • AvaloniaRenderingFrameProvider

Calling AvaloniaProviderInitializer.SetDefaultObservableSystem() at startup will replace ObservableSystem.DefaultTimeProvider and ObservableSystem.DefaultFrameProvider with AvaloniaDispatcherTimeProvider and AvaloniaDispatcherFrameProvider.

Additionally, calling UseR3() in AppBuilder sets the default providers, making it a recommended approach.

public static AppBuilder BuildAvaloniaApp()
    => AppBuilder.Configure<App>()
        .UsePlatformDetect()
        .WithInterFont()
        .LogToTrace()
        .UseR3(); // add this line

As a result, time based operations are replaced with DispatcherTimer, allowing you to reflect time based operations on the UI without having to use ObserveOn.

In the case of methods without arguments, integrate the following method into ObservableSystem.RegisterUnhandledExceptionHandler. Please customize this as necessary.

ex => Logger.Sink?.Log(LogEventLevel.Error, "R3", null, "R3 Unhandled Exception {0}", ex);

AvaloniaDispatcherFrameProvider calculates a frame by polling with DispatcherTimer. By default, it updates at 60fps.

Using AvaloniaRenderingFrameProvider is more performant however it needs TopLevel.

public partial class MainWindow : Window
{
    AvaloniaRenderingFrameProvider frameProvider;

    public MainWindow()
    {
        InitializeComponent();

        // initialize RenderingFrameProvider
        var topLevel = TopLevel.GetTopLevel(this);
        this.frameProvider = new AvaloniaRenderingFrameProvider(topLevel!);
    }

    protected override void OnLoaded(RoutedEventArgs e)
    {
        // pass frameProvider
        Observable.EveryValueChanged(this, x => x.Width, frameProvider)
            .Subscribe(x => textBlock.Text = x.ToString());
    }

    protected override void OnClosed(EventArgs e)
    {
        frameProvider.Dispose();
    }
}

In addition to the above, the following ObserveOn/SubscribeOn methods have been added.

  • ObserveOnDispatcher
  • ObserveOnUIThreadDispatcher
  • SubscribeOnDispatcher
  • SubscribeOnUIThreadDispatcher

Uno

PM> Install-Package R3Extensions.Uno

R3Extensions.Uno package has two providers.

  • UnoDispatcherTimeProvider
  • UnoRenderingFrameProvider

Calling UnoProviderInitializer.SetDefaultObservableSystem() at startup will replace ObservableSystem.DefaultTimeProvider and ObservableSystem.DefaultFrameProvider with UnoDispatcherTimeProvider and UnoRenderingFrameProvider.

Additionally, calling UseR3() in ApplicationBuilder sets the default providers, making it a recommended approach.

public partial class App : Application
{
    protected async override void OnLaunched(LaunchActivatedEventArgs args)
    {
        var builder = this.CreateBuilder(args)
            .UseR3() // add this line
            ...
    }
}

As a result, time based operations are replaced with DispatcherTimer, allowing you to reflect time based operations on the UI without having to use ObserveOn.

In the case of methods without arguments, integrate the following method into ObservableSystem.RegisterUnhandledExceptionHandler. Please customize this as necessary.

ex => builder.Log().LogError("R3 Unhandled Exception {0}", ex));

In addition to the above, the following ObserveOn/SubscribeOn methods have been added.

  • ObserveOnDispatcher
  • ObserveOnCurrentWindowDispatcher
  • SubscribeOnDispatcher
  • SubscribeOnCurrentWindowDispatcher

MAUI

PM> Install-Package R3Extensions.Maui

R3Extensions.Maui package has these providers.

  • MauiDispatcherTimeProvider
  • MauiTickerFrameProvider

And ViewModel binding is supported, see BindableReactiveProperty<T> section.

Calling UseR3() in MauiAppBuilder sets the default providers.

public static MauiApp CreateMauiApp()
{
    var builder = MauiApp.CreateBuilder();
    builder
        .UseMauiApp<App>()
        .ConfigureFonts(fonts =>
        {
            fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
            fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
        })
        .UseR3(); // add this line

    return builder.Build();
}

UseR3() configures the following.

  • Time based operations are replaced with IDispatcher, allowing you to reflect time based operations on the UI without having to use ObserveOn.
  • Frame based operations are replaced with Ticker.
  • ObservableSystem.RegisterUnhandledExceptionHandler is set to R3MauiDefaultExceptionHandler:
    • public class R3MauiDefaultExceptionHandler(IServiceProvider serviceProvider) : IR3MauiExceptionHandler
      {
          public void HandleException(Exception ex)
          {
              System.Diagnostics.Trace.TraceError("R3 Unhandled Exception {0}", ex);
      
              var logger = serviceProvider.GetService<ILogger<R3MauiDefaultExceptionHandler>>();
              logger?.LogError(ex, "R3 Unhandled Exception");
          }
      }
      

If you want to customize the ExceptionHandler, there are two ways.

One is to pass a callback to `UseR3e

builder.UseR3(ex => Console.WriteLine($"R3 UnhandledException:{ex}"));

The second is to create an implementation of the IR3MAuiExceptionHandler interface and DI it. Since MAUI is a DI-based framework, this method will make it easier to access the various functions in the DI container.

builder.Services.AddSingleton<IR3MauiExceptionHandler, YourCustomExceptionHandler>();

WinForms

PM> Install-Package R3Extensions.WinForms

R3Extensions.WinForms package has these providers.

  • WinFormsFrameProvider
  • WinFormsTimeProvider

Calling WinFormsProviderInitializer.SetDefaultObservableSystem() at startup(Program.Main) will replace ObservableSystem.DefaultTimeProvider and ObservableSystem.DefaultFrameProvider with WinFormsFrameProvider and WinFormsTimeProvider.

using R3.WinForms;

internal static class Program
{
    [STAThread]
    static void Main()
    {
        ApplicationConfiguration.Initialize();

        var form = new Form1();

        // add this line
        WinFormsProviderInitializer.SetDefaultObservableSystem(ex => Trace.WriteLine($"R3 UnhandledException:{ex}"), form);

        Application.Run(form);
    }
}

SetDefaultObservableSystem takes ISynchronizeInvoke (such as Form or Control). This makes the Timer operate on the thread to which it belongs.

FrameProvider is executed as one frame using the hook of MessageFilter.

WinUI3

PM> Install-Package R3Extensions.WinUI3

R3Extensions.WinUI3 package has these providers.

  • WinUI3DispatcherTimeProvider
  • WinUI3RenderingFrameProvider

Calling WinUI3ProviderInitializer.SetDefaultObservableSystem() at startup will replace ObservableSystem.DefaultTimeProvider and ObservableSystem.DefaultFrameProvider with the aforementioned providers.

public partial class App : Application
{
    public App()
    {
        this.InitializeComponent();

        // Add this line.
        // You need to set UnhandledExceptionHandler
        WinUI3ProviderInitializer.SetDefaultObservableSystem(ex => Trace.WriteLine(ex.ToString()));
    }

    // OnLaunched...
}

Unity

The minimum Unity support for R3 is Unity 2021.3.

There are two installation steps required to use it in Unity.

  1. Install R3 from NuGet using NuGetForUnity
  • Open Window from NuGet → Manage NuGet Packages, Search "R3" and Press Install.