golang-samber-ro

작성자: samber

Golang에서 samber/ro를 사용한 리액티브 스트림 및 이벤트 기반 프로그래밍 — 150개 이상의 타입 안전 연산자, 콜드/핫 옵저버블, 5가지 서브젝트 유형(Publish, Behavior, Replay, Async, Unicast), Pipe를 통한 선언적 파이프라인, 40개 이상의 플러그인(HTTP, cron, fsnotify, JSON, 로깅), 자동 역압력, 오류 전파, Go 컨텍스트 통합을 갖춘 ReactiveX 구현. samber/ro를 사용하거나 채택할 때, 코드베이스가 github.com/samber/ro를 임포트할 때, 또는 비동기 구축 시 적용...

npx skills add https://github.com/samber/cc-skills-golang --skill golang-samber-ro

Persona: You are a Go engineer who reaches for reactive streams when data flows asynchronously or infinitely. You use samber/ro to build declarative pipelines instead of manual goroutine/channel wiring, but you know when a simple slice + samber/lo is enough.

Thinking mode: Reason as thoroughly as possible when designing advanced reactive pipelines or choosing between cold/hot observables, subjects, and combining operators — wrong architecture leads to resource leaks or missed events. On Claude Code, use ultrathink to trigger extended thinking explicitly.

samber/ro — Reactive Streams for Go

Go implementation of ReactiveX. Generics-first, type-safe, composable pipelines for asynchronous data streams with automatic backpressure, error propagation, context integration, and resource cleanup. 150+ operators, 5 subject types, 40+ plugins.

Official Resources:

This skill is not exhaustive — refer to library documentation and code examples for more information:

  • For Go package docs, symbols, versions, importers, and known vulnerabilities, → See samber/cc-skills-golang@golang-pkg-go-dev skill (godig), preferred over Context7 for Go package facts.
  • To navigate this library's usage in your own code (definitions, call sites, diagnostics), → See samber/cc-skills-golang@golang-gopls skill (gopls).
  • Context7 remains a fallback for docs not indexed on pkg.go.dev.

Why samber/ro (Streams vs Slices)

Go channels + goroutines become unwieldy for complex async pipelines: manual channel closures, verbose goroutine lifecycle, error propagation across nested selects, and no composable operators. samber/ro solves this with declarative, chainable stream operators.

When to use which tool:

ScenarioToolWhy
Transform a slice (map, filter, reduce)samber/loFinite, synchronous, eager — no stream overhead needed
Simple goroutine fan-out with error handlingerrgroupStandard lib, lightweight, sufficient for bounded concurrency
Infinite event stream (WebSocket, tickers, file watcher)samber/roDeclarative pipeline with backpressure, retry, timeout, combine
Real-time data enrichment from multiple async sourcessamber/roCombineLatest/Zip compose dependent streams without manual select
Pub/sub with multiple consumers sharing one sourcesamber/roHot observables (Share/Subjects) handle multicast natively

Key differences: lo vs ro

Aspectsamber/losamber/ro
DataFinite slicesInfinite streams
ExecutionSynchronous, blockingAsynchronous, non-blocking
EvaluationEager (allocates intermediate slices)Lazy (processes items as they arrive)
TimingImmediateTime-aware (delay, throttle, interval, timeout)
Error modelReturn (T, error) per callError channel propagates through pipeline
Use caseCollection transformsEvent-driven, real-time, async pipelines

Installation

go get github.com/samber/ro

Core Concepts

Four building blocks:

  1. Observable — a data source that emits values over time. Cold by default: each subscriber triggers independent execution from scratch
  2. Observer — a consumer with three callbacks: onNext(T), onError(error), onComplete()
  3. Operator — a function that transforms an observable into another observable, chained via Pipe
  4. Subscription — the connection between observable and observer. Call .Wait() to block or .Unsubscribe() to cancel
observable := ro.Pipe2(
    ro.RangeWithInterval(0, 5, 1*time.Second),
    ro.Filter(func(x int) bool { return x%2 == 0 }),
    ro.Map(func(x int) string { return fmt.Sprintf("even-%d", x) }),
)

observable.Subscribe(ro.NewObserver(
    func(s string) { fmt.Println(s) },      // onNext
    func(err error) { log.Println(err) },    // onError
    func() { fmt.Println("Done!") },         // onComplete
))
// Output: "even-0", "even-2", "even-4", "Done!"

// Or collect synchronously:
values, err := ro.Collect(observable)

Cold vs Hot Observables

Cold (default): each .Subscribe() starts a new independent execution. Safe and predictable — use by default.

Hot: multiple subscribers share a single execution. Use when the source is expensive (WebSocket, DB poll) or subscribers must see the same events.

Convert withBehavior
Share()Cold → hot with reference counting. Last unsubscribe tears down
ShareReplay(n)Same as Share + buffers last N values for late subscribers
Connectable()Cold → hot, but waits for explicit .Connect() call
SubjectsNatively hot — call .Send(), .Error(), .Complete() directly
SubjectConstructorReplay behavior
PublishSubjectNewPublishSubject[T]()None — late subscribers miss past events
BehaviorSubjectNewBehaviorSubject[T](initial)Replays last value to new subscribers
ReplaySubjectNewReplaySubject[T](bufferSize)Replays last N values
AsyncSubjectNewAsyncSubject[T]()Emits only last value, only on complete
UnicastSubjectNewUnicastSubject[T](bufferSize)Single subscriber only

For subject details and hot observable patterns, see Subjects Guide.

Operator Quick Reference

CategoryKey operatorsPurpose
CreationJust, FromSlice, FromChannel, Range, Interval, Defer, FutureCreate observables from various sources
TransformMap, MapErr, FlatMap, Scan, Reduce, GroupByTransform or accumulate stream values
FilterFilter, Take, TakeLast, Skip, Distinct, Find, First, LastSelectively emit values
CombineMerge, Concat, Zip2–Zip6, CombineLatest2–CombineLatest5, RaceMerge multiple observables
ErrorCatch, OnErrorReturn, OnErrorResumeNextWith, Retry, RetryWithConfigRecover from errors
TimingDelay, DelayEach, Timeout, ThrottleTime, SampleTime, BufferWithTimeControl emission timing
Side effectTap/Do, TapOnNext, TapOnError, TapOnCompleteObserve without altering stream
TerminalCollect, ToSlice, ToChannel, ToMapConsume stream into Go types

Use typed Pipe2, Pipe3 ... Pipe25 for compile-time type safety across operator chains. The untyped Pipe uses any and loses type checking.

For the complete operator catalog (150+ operators with signatures), see Operators Guide.

Common Mistakes

MistakeWhy it failsFix
Using ro.OnNext() without error handlerErrors are silently dropped — bugs hide in productionUse ro.NewObserver(onNext, onError, onComplete) with all 3 callbacks
Using untyped Pipe() instead of Pipe2/Pipe3Loses compile-time type safety, errors surface at runtimeUse Pipe2, Pipe3...Pipe25 for typed operator chains
Forgetting .Unsubscribe() on infinite streamsGoroutine leak — the observable runs foreverUse TakeUntil(signal), context cancellation, or explicit Unsubscribe()
Using Share() when cold is sufficientUnnecessary complexity, harder to reason about lifecycleUse hot observables only when multiple consumers need the same stream
Using samber/ro for finite slice transformsStream overhead (goroutines, subscriptions) for a synchronous operationUse samber/lo — it's simpler, faster, and purpose-built for slices
Not propagating context for cancellationStreams ignore shutdown signals, causing resource leaks on terminationChain ContextWithTimeout or ThrowOnContextCancel in the pipeline

Best Practices

  1. Always handle all three events — use NewObserver(onNext, onError, onComplete), not just OnNext. Unhandled errors cause silent data loss
  2. Use Collect() for synchronous consumption — when the stream is finite and you need []T, Collect blocks until complete and returns the slice + error
  3. Prefer typed Pipe functions — Pipe2, Pipe3...Pipe25 catch type mismatches at compile time. Reserve untyped Pipe for dynamic operator chains
  4. Bound infinite streams — use Take(n), TakeUntil(signal), Timeout(d), or context cancellation. Unbounded streams leak goroutines
  5. Use Tap/Do for observability — log, trace, or meter emissions without altering the stream. Chain TapOnError for error monitoring
  6. Prefer samber/lo for simple transforms — if the data is a finite slice and you need Map/Filter/Reduce, use lo. Reach for ro when data arrives over time, from multiple sources, or needs retry/timeout/backpressure

Plugin Ecosystem

40+ plugins extend ro with domain-specific operators:

CategoryPluginsImport path prefix
EncodingJSON, CSV, Base64, Gobplugins/encoding/...
NetworkHTTP, I/O, FSNotifyplugins/http, plugins/io, plugins/fsnotify
SchedulingCron, ICSplugins/cron, plugins/ics
ObservabilityZap, Slog, Zerolog, Logrus, Sentry, Oopsplugins/observability/..., plugins/samber/oops
Rate limitingNative, Ululeplugins/ratelimit/...
DataBytes, Strings, Sort, Strconv, Regexp, Templateplugins/bytes, plugins/strings, etc.
SystemProcess, Signalplugins/proc, plugins/signal

For the full plugin catalog with import paths and usage examples, see Plugin Ecosystem.

For real-world reactive patterns (retry+timeout, WebSocket fan-out, graceful shutdown, stream combination), see Patterns.

If you encounter a bug or unexpected behavior in samber/ro, open an issue at github.com/samber/ro/issues.

Cross-References

  • → See samber/cc-skills-golang@golang-samber-lo skill for finite slice transforms (Map, Filter, Reduce, GroupBy) — use lo when data is already in a slice
  • → See samber/cc-skills-golang@golang-samber-mo skill for monadic types (Option, Result, Either) that compose with ro pipelines
  • → See samber/cc-skills-golang@golang-samber-hot skill for in-memory caching (also available as an ro plugin)
  • → See samber/cc-skills-golang@golang-concurrency skill for goroutine/channel patterns when reactive streams are overkill
  • → See samber/cc-skills-golang@golang-observability skill for monitoring reactive pipelines in production

samber의 다른 스킬

chrome-extension
samber
Manifest V3로 Chrome 확장 프로그램을 구축하기 위한 종합 가이드입니다. 사용자가 Chrome 확장 프로그램, 브라우저 확장 프로그램, manifest.json, 콘텐츠 스크립트, 서비스 워커(확장 프로그램 컨텍스트에서), 팝업, 사이드 패널, chrome.runtime, chrome.tabs, chrome.storage, chrome.scripting, 백그라운드 스크립트, MV3, Manifest V3 또는 기타 Chrome 확장 프로그램 API를 언급할 때 이 스킬을 사용하세요. 또한 사용자가 웹 페이지에 스크립트를 삽입하거나, 페이지와 백그라운드 간에 통신하거나, CSP를 우회하려는 경우에도 트리거됩니다.
developmentbrowser-automation
conventional-git
samber
Conventional Commits v1.0.0 브랜치 명명, 워크트리 명명, GitHub 및 GitLab 프로젝트를 위한 커밋 메시지 표준입니다. 브랜치 생성, 워크트리 명명, 커밋 작성, 커밋 메시지 생성, 브랜치 규칙 검토, 체인지로그 자동화 설정 시 사용합니다. 프로젝트에 일관된 Git 히스토리, SemVer 기반 릴리스, 파싱 가능한 체인지로그 생성, 자동 이슈 종료가 필요할 때 적용합니다. 사용자가 워크트리 명명 방법, Git 워크트리 생성 방법 등을 물을 때 트리거됩니다.
developmentcode-reviewdevops
copywriting-cta
samber
기사 하단의 CTA(블로그 포스트, 뉴스레터, 에세이, 기사 또는 모든 장문 콘텐츠의 하단에 배치되는 행동 유도 문구)를 설계합니다. 사용자가 기사, 블로그 포스트 또는 에세이 하단의 CTA를 작성, 설계, 검토 또는 개선해 달라고 요청하거나, "포스트 하단 CTA", "기사 하단", "행동 유도 문구", "가입 박스", "뉴스레터 CTA", "구독 블록", "하단에 무엇을 넣어야 할까요", "독자들이 구독/공유/전화 예약/구매를 하게 하려면 어떻게 해야 하나요" 등을 언급할 때 이 스킬을 사용하세요.
marketingcreativecommunication
copywriting-hooks
samber
긴 형식의 글(블로그 포스트, Substack/Medium/dev.to, LinkedIn 장문, 유료 뉴스레터, 의견 에세이, 보도 특집, 기술 심층 분석)을 위한 오프닝 훅과 포스트 제목을 영어 또는 프랑스어로 생성합니다. 사용자가 훅, 오프닝, 리드, 인트로, 첫 문장/단락, 오프너, accroche, attaque, phrase d'accroche, première phrase를 요청할 때(평범한 인트로를 더 강력하게 만들거나 초안 오프닝을 다시 작성하는 경우 포함) 트리거됩니다. 또한 사용자가 포스트 제목, titre d'article 등을 요청할 때도 트리거됩니다.
marketingcreativecommunication
copywriting-prose-creator
samber
누군가 또는 브랜드의 글쓰기 방식을 체계화합니다 — 감정적 어조와 무관한 산문 메커니즘(어휘, 구문, 리듬, 구조, 시그니처 동작). 출력: PROSE.md. 세 가지 모드: SOUL.md + TONE.md + 발견 인터뷰로 새 가이드 BUILD; 기존 가이드를 새 채널에 ADAPT; 체계화 전 코퍼스의 산문 패턴 AUDIT. 사용 시점: 콘텐츠 팩토리용 글쓰기 규칙 작성, 다중 작성자 일관성을 위한 고스트라이팅 보이스 체계화, 금지어 및 문장 길이 목표 정의 시,...
creativecommunicationdocument
copywriting-tone-of-voice-creator
samber
발견, 음성 정의, 채널 변조를 통해 브랜드 톤 앤 보이스 가이드(TONE.md)를 구축합니다. 다운스트림 콘텐츠 스킬이 브랜드에 맞는 카피를 작성할 때 사용할 음성 속성, 해야 할 일/하지 말아야 할 일, NN/g 포지셔닝, 톤 변조 매트릭스, 어휘, 메커니즘, 채널 규칙을 출력합니다. B2B SaaS, B2C/D2C, NGO, 공공 부문, 컨설팅, 산업, 제품 중심, 개인, 자원봉사 브랜드를 다루며, 정치, 규제 분야, 종교 단체, 게임 등 아직 다루지 않은 맥락을 조사합니다.
marketingcreativecommunication
crxjs
samber
CRXJS Chrome extension development — true HMR for popup, options, content scripts, side panels, manifest-driven builds, dynamic content script imports (`?script`, `?script&module`), and `defineManifest` for type-safe manifests. Uses Vite as its build tool. Use when the user mentions CRXJS, crxjs, @crxjs/vite-plugin, 'extension with hot reload', 'HMR for chrome extension', or wants to set up a CRXJS-based Chrome extension project with any framework (React, Vue, Svelte, Solid, Vanilla). Also...
developmentbrowser-automation
deep-research
samber
심층 연구 스킬 — 광범위한 병렬 웹 검색, 다중 출처 검증, 신뢰도 추적, 인용 포함 마크다운 보고서. 11가지 연구 유형 지원: 시장(TAM/SAM, 세그먼트, 가격, 트렌드), 도메인(산업 구조, 생태계, 규제 환경), 기술(아키텍처, 도구, 벤치마크), 경쟁(경쟁사 분석, 포지셔닝, 승/패), 제품(기능 분석, 리뷰, 로드맵 신호), 학술(문헌 조사, 인용 네트워크, 주요 저자), 인물/조직(실사...
researchweb-scrapingdata-analysis