Skip to content

samber/cc-skills-golang / skills/golang-samber-ro

golang-samber-ro

Verified

Reactive streams and event-driven programming in Golang using samber/ro — ReactiveX implementation with 150+ type-safe operators, cold/hot observables, 5 subject types (Publish, Behavior, Replay, Async, Unicast), declarative pipelines via Pipe, 40+ plugins (HTTP, cron, fsnotify, JSON, logging), automatic backpressure, error propagation, and Go context integration. Apply when using or adopting samber/ro, when the codebase imports github.com/samber/ro, or when building asynchronous event-driven pipelines, real-time data processing, streams, or reactive architectures in Go. Not for finite slice transforms (→ See `samber/cc-skills-golang@golang-samber-lo` skill).

FileKindSize
SKILL.mdskill md11.8 KB
evals/evals.jsonconfig17.3 KB
references/operators-guide.mdmarkdown14.6 KB
references/patterns.mdmarkdown8.0 KB
references/plugin-ecosystem.mdmarkdown6.3 KB
references/subjects-guide.mdmarkdown6.3 KB

references/subjects-guide.md

View on GitHub
# Subjects Guide

Subjects are both Observable and Observer — they can receive values (via `Send`, `Error`, `Complete`) and be subscribed to. Subjects are natively **hot**: subscribers share a single execution, and late subscribers only see future emissions (unless replay is configured).

## Table of Contents

- [When to Use Subjects vs Cold Observables](#when-to-use-subjects-vs-cold-observables)
- [Subject Types](#subject-types)
  - [PublishSubject](#publishsubject)
  - [BehaviorSubject](#behaviorsubject)
  - [ReplaySubject](#replaysubject)
  - [AsyncSubject](#asyncsubject)
  - [UnicastSubject](#unicastsubject)
- [Cold to Hot Conversion](#cold-to-hot-conversion)
  - [Share](#share)
  - [ShareReplay](#sharereplay)
  - [Connectable Observable](#connectable-observable)
- [Subject Decision Table](#subject-decision-table)
- [Common Subject Mistakes](#common-subject-mistakes)

## When to Use Subjects vs Cold Observables

| Use case | Approach |
| --- | --- |
| Data pipeline from a known source (slice, channel, HTTP) | Cold observable (default) |
| Event bus where producers and consumers are decoupled | Subject |
| Multiple consumers need the same WebSocket/ticker stream | Cold observable + `Share()` or `ShareReplay()` |
| Imperatively push values from non-reactive code | Subject |
| Bridge between callback API and reactive pipeline | Subject (receive callbacks, emit to pipeline) |

## Subject Types

### PublishSubject

Standard multicast. Subscribers only see values emitted **after** they subscribe.

```go
subject := ro.NewPublishSubject[string]()

// Subscriber 1
subject.Subscribe(ro.OnNext(func(s string) {
    fmt.Println("sub1:", s)
}))

subject.Send("hello")  // sub1 sees this

// Subscriber 2 (late)
subject.Subscribe(ro.OnNext(func(s string) {
    fmt.Println("sub2:", s)
}))

subject.Send("world")  // both see this
subject.Complete()
```

**Use when:** broadcasting events where late subscribers don't need history — UI events, log streams, notifications.

### BehaviorSubject

Replays the **last emitted value** (or the initial value) to every new subscriber immediately on subscription.

```go
subject := ro.NewBehaviorSubject[int](0) // initial value = 0

// Subscriber 1 immediately receives 0
subject.Subscribe(ro.OnNext(func(v int) {
    fmt.Println("sub1:", v) // 0, then 42
}))

subject.Send(42)

// Subscriber 2 immediately receives 42 (latest value)
subject.Subscribe(ro.OnNext(func(v int) {
    fmt.Println("sub2:", v) // 42
}))
```

**Use when:** subscribers need the current state — config values, connection status, latest price.

### ReplaySubject

Buffers the last **N values** and replays them to every new subscriber.

```go
subject := ro.NewReplaySubject[string](3) // buffer size = 3

subject.Send("a")
subject.Send("b")
subject.Send("c")
subject.Send("d") // "a" evicted from buffer

// Late subscriber receives "b", "c", "d" (last 3)
subject.Subscribe(ro.OnNext(func(s string) {
    fmt.Println(s)
}))
```

**Use when:** late subscribers need recent history — chat messages, recent logs, last N stock ticks.

### AsyncSubject

Emits **only the last value** and only when the subject completes. If the subject errors, no value is emitted.

```go
subject := ro.NewAsyncSubject[int]()

subject.Subscribe(ro.NewObserver(
    func(v int) { fmt.Println(v) },    // receives 3 only
    func(err error) { },
    func() { fmt.Println("done") },
))

subject.Send(1)
subject.Send(2)
subject.Send(3)
subject.Complete() // triggers emission of 3, then "done"
```

**Use when:** only the final result matters — computation result, last response in a batch.

### UnicastSubject

Allows exactly **one subscriber**. Buffers values internally until that subscriber connects.

```go
subject := ro.NewUnicastSubject[int](100) // buffer size

subject.Send(1) // buffered
subject.Send(2) // buffered

// Single subscriber receives buffered + future values
subject.Subscribe(ro.OnNext(func(v int) {
    fmt.Println(v) // 1, 2, then future values
}))
// Second subscribe would panic or error
```

**Use when:** single consumer with buffering — job queues, request pipelines where exactly one handler processes events.

## Cold to Hot Conversion

When you have a cold observable (e.g. an HTTP request) but need multiple subscribers to share it:

### Share

```go
// Each subscriber to `cold` would trigger a separate HTTP request
cold := httpPlugin.Get[Data](url)

// Share: single execution, multiple subscribers
hot := ro.Pipe1(cold, ro.Share[Data]())

hot.Subscribe(uiObserver)       // shares one HTTP call
hot.Subscribe(metricsObserver)  // same data, no extra request
```

`Share` uses reference counting: the source subscribes when the first subscriber arrives and unsubscribes when the last one leaves.

### ShareReplay

```go
// Late subscribers get the last N values + future values
hot := ro.Pipe1(cold, ro.ShareReplay[Data](1))
```

### Connectable Observable

For precise control over when the shared subscription starts:

```go
connectable := ro.Connectable[Data](cold)

// Set up subscribers first
connectable.Subscribe(observer1)
connectable.Subscribe(observer2)

// Start the shared execution explicitly
sub, err := connectable.Connect(ctx)
```

## Subject Decision Table

| Subject | Replay | Subscribers | Use case |
| --- | --- | --- | --- |
| `PublishSubject` | None | Many | Event bus, notifications |
| `BehaviorSubject` | Last 1 (+ initial) | Many | Current state, config |
| `ReplaySubject` | Last N | Many | Recent history, chat |
| `AsyncSubject` | Last 1 (on complete) | Many | Final computation result |
| `UnicastSubject` | Buffered (pre-subscribe) | Exactly 1 | Single-consumer queue |

## Common Subject Mistakes

| Mistake | Why | Fix |
| --- | --- | --- |
| Calling `Send()` after `Complete()` | Values are silently dropped — the subject is terminal | Track lifecycle, don't reuse completed subjects |
| Using PublishSubject when late subscribers need history | Late subscribers miss all prior events | Use BehaviorSubject (last 1) or ReplaySubject (last N) |
| Using ReplaySubject with unbounded buffer | Memory grows without limit | Set an explicit `bufferSize` |
| Multiple subscribers on UnicastSubject | Panics or undefined behavior | Use PublishSubject for multicast, UnicastSubject for single consumer |
| Not calling `Complete()` on subjects | Subscribers wait forever, goroutine leak | Always `Complete()` or `Error()` when the source is done |
writing-skillsobra/superpowersUse when creating new skills, editing existing skills, or verifying skills work before deploymentStars: 323kUpdated Claude CodeCodexVerifiedInstall
xlsxanthropics/skillsUse this skill any time a spreadsheet file is the primary input or output. This means any task where the user wants to: open, read, edit, or fix an existing .xlsx, .xlsm, .xltx, .csv, or .tsv file (e.g., adding columns, computing formulas, formatting, charting, cleaning messy data); create a new spreadsheet from scratch or from other data sources; or convert between tabular file formats. Trigger especially when the user references a spreadsheet file by name or path — even casually (like "the xlsx in my downloads") — and wants something done to it or produced from it. Also trigger for cleaning or restructuring messy tabular data files (malformed rows, misplaced headers, junk data) into proper spreadsheets. The deliverable must be a spreadsheet file. Do NOT trigger when the primary deliverable is a Word document, HTML report, standalone Python script, database pipeline, or Google Sheets API integration, even if tabular data is involved.Stars: 198kUpdated Claude CodeCodexVerifiedInstall
shipping-and-launchaddyosmani/agent-skillsPrepares production launches. Use when preparing to deploy to production, or when asking what needs to be in place before shipping. Use when you need a pre-launch checklist, when setting up monitoring, when planning a staged rollout, or when you need a rollback strategy.Stars: 119kUpdated Claude CodeCodexVerifiedInstall
childhoodthedotmack/claude-memBabysit a shipped release after merge, publication, or deployment. Verify published packages, production behavior, installed plugins, and late CI or user reports until the observation window is clean; use babysit for PR readiness before release.Stars: 118kUpdated Claude CodeCodexVerifiedInstall