Course contentsShow
← C#
Lesson 1417 of 1,90812. Modern Frontend with Razor and BlazorFree lesson

Reactive UI Paradigms

Apply observable patterns to update the UI reactively based on data stream changes.

In this lesson, you will learn how to decouple your Blazor component logic from UI updates by using IObservable<T> to stream data changes directly into your view.

Moving Beyond Manual State Management

In traditional Blazor components, you often find yourself calling StateHasChanged() inside event handlers or data callbacks. This approach quickly becomes brittle as your data dependencies grow. A Reactive UI Paradigm treats your data not as a static variable, but as a continuous stream of events. By using System.Reactive (Rx.NET), you can transform these streams and push updates to the UI only when necessary.

Reactive Streams in Components

Instead of manually updating a property and triggering a re-render, we subscribe to an IObservable stream. When the stream emits a value, we update the component's state and notify the renderer.

Consider a component that displays a live sensor reading:

@implements IDisposable
@inject IObservable<double> SensorStream

<p>Current Reading: @currentValue</p>

@code {
    private double currentValue;
    private IDisposable subscription;

    protected override void OnInitialized()
    {
        subscription = SensorStream
            .Sample(TimeSpan.FromMilliseconds(500))
            .Subscribe(val => {
                currentValue = val;
                InvokeAsync(StateHasChanged);
            });
    }

    public void Dispose() => subscription?.Dispose();
}

Why This Matters

By utilizing reactive operators like .Sample(), .Throttle(), or .Select(), you can refine how frequently your UI reacts to high-frequency data. This shifts the responsibility of "when to update" from the business logic into the data pipeline itself. Your component becomes a passive observer, significantly reducing the surface area for bugs caused by out-of-sync state or excessive rendering cycles. This pattern keeps your Razor markup clean and ensures your UI remains performant, even when handling complex, real-time data streams.

Key Takeaway: Adopting reactive paradigms allows your UI to act as a reactive observer of data streams, automating state updates and drastically simplifying component lifecycle management.