Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

rx-observables

БесплатноБез исполняемых скриптовНе проверен

Use when writing, editing, or reviewing C# code that uses System.Reactive (Rx.NET); working with `IObservable`, `IObserver`, `Subject`, `BehaviorSubject`…

recyclarrот recyclarr★ 2 180 звёзд на GitHub

Об этом скилле

Rx.NET Patterns and Practices

Patterns, anti-patterns, and decision guidance for System.Reactive (Rx.NET) in C#. Covers interface design, subject usage, subscription lifecycle, error handling, and testing.

Exposing Observables

Expose IObservable<T> as a property; never inherit from it.

Classes should not implement IObservable<T> directly. Expose a property instead, enabling consumers to compose operators before subscribing.

public class SensorReadings
{
    private readonly Subject<double> _readings = new();

    // Wrap with AsObservable() to prevent downcasting to Subject
    public IObservable<double> Readings => _readings.AsObservable();

    internal void Report(double value) => _readings.OnNext(value);
}

Key rules:

  • Always call AsObservable() on subjects before exposing them. This prevents consumers from calling OnNext/OnError/OnCompleted.
  • Never return null from a method or property typed IObservable<T>. Return Observable.Empty<T>() or Observable.Never<T>() instead.
  • Avoid implementing IObservable<T> or IObserver<T> yourself. Use Observable.Create or subjects.

Subject Selection

Subjects are "mutable variables of the Rx world" (Erik Meijer). Use them only to generate a hot observable imperatively from a local source with no direct external observable to adapt.

Decision: Subject vs Observable.Create

Use Observable.Create when:

  • Wrapping an external async/callback/event source into an observable
  • Each subscriber needs independent state (cold observable)
  • Cleanup logic ties naturally to the subscription's IDisposable

Use a Subject when:

  • You need to imperatively push values from code you control (local source)
  • Multiple subscribers must share the same live stream (hot observable)
  • Modeling property-change or event-like notifications

If the source is an existing observable and you want hot behavior, use Publish/RefCount instead of piping through a subject.

Which Subject Type

Type Replays Seed Use when
Subject<T> None No Fire-and-forget events; no history needed
BehaviorSubject<T> Last (1) Yes Property-change semantics; always has current value
ReplaySubject<T> N or all No Late subscribers need historical values
AsyncSubject<T> Last No Single async result (like Task<T>)

BehaviorSubject<T> requires a seed value and immediately pushes it to new subscribers. Prefer it for "current state" scenarios.

ReplaySubject<T> can replay a bounded window (new ReplaySubject<T>(bufferSize)) or a time window. Always bound the buffer to avoid unbounded memory growth.

Subjects Must Be Private

Subjects are implementation details. Expose only IObservable<T> publicly:

private readonly BehaviorSubject<int> _count = new(0);
public IObservable<int> Count => _count.AsObservable();

Imperative Read-back Is a Design Smell

Exposing .Value / .Current from a BehaviorSubject<T> publicly introduces imperatively-accessed shared state, undermining the reactive model. Ben Lesh (RxJS lead): "using getValue() is a huge code smell... you're doing something imperative in declarative paradigm."

Acceptable: Internal read-modify-write within the owning class (e.g. _subject.OnNext(_subject.Value + 1)).

Avoid: Public .Value properties that let consumers pull state instead of subscribing.

Alternatives:

  • Pass data as parameters to consumers instead of letting them read state.
  • Use Scan within the observable chain for stateful accumulation.
  • Use an OAPH-like pattern (subscribe internally, cache latest, expose read-only) when a synchronous read is genuinely necessary.

Hot vs Cold Observables

Cold: Each Subscribe triggers independent execution. Factory methods like Observable.Create, Observable.Defer, Observable.Timer produce cold observables.

Hot: All subscribers share a single underlying source. Subjects are inherently hot. Use Publish/RefCount to share a cold source:

IObservable<long> shared = Observable
    .Interval(TimeSpan.FromSeconds(1))
    .Publish()
    .RefCount();

Publish().RefCount() connects on first subscriber and disconnects when the last unsubscribes. Use Publish().AutoConnect(n) if you need to wait for n subscribers before connecting.

Subscription Lifecycle

Every Subscribe returns an IDisposable. Failing to dispose leaks subscriptions and can leak the subscriber (prevented from GC by the observable's reference to it).

Disposable Types

Type Behavior
`CompositeD
Полный SKILL.md на GitHub

Установить rx-observables в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

FAQ

Что делает скилл rx-observables?

Use when writing, editing, or reviewing C# code that uses System.Reactive (Rx.NET); working with `IObservable`, `IObserver`, `Subject`, `BehaviorSubject`, `ReplaySubject`, or `AsyncSubject`; composing operators like `Select`, `Where`, `Merge`, `Switch`, `Publish`, `RefCount`, `Catch`, `Retry`, `ObserveOn`, or `SubscribeOn`; managing subscription lifecycle with `CompositeDisposable`, `SerialDisposable`, or `DisposeWith`; testing time-dependent reactive code with `TestScheduler` from `Microsoft.Reactive.Testing`; designing hot vs cold observables or enforcing the Rx serial-notification contract. Triggers on phrases like "observable stream", "reactive pipeline", "Rx.NET", "subject leak", "OnNext on wrong thread", "test scheduler", or edits touching files that import `System.Reactive`. Do NOT use for plain `IEnumerable` LINQ, `IAsyncEnumerable`, or TPL `Task`-based async.

Как установить скилл rx-observables?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл rx-observables запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить rx-observables с