luminyra
Guides

Operators and ways to consume a stream

Compose operators in order, compare accumulation with reduction, and use iterators or callbacks.

Compose operators

The example generates numbers with Range, filters for multiples of three, squares them, limits the count, and collects with Observable.Collect. The pipeline runs in method order, with each transformation feeding the next.

rx/examples/pipeline/main.go
// Multiples of 3 between 1 and 20, squared, first four only. Operators
// are methods, so the pipeline reads left to right.
squares := rx.Range(1, 20).
	Filter(func(n int) bool { return n%3 == 0 }).
	Map(func(n int) int { return n * n }).
	Take(4)
values, err := squares.Collect(ctx)
View on GitHub

Compare intermediate and final results

Observable.Scan emits the result of each accumulation step, such as progressively building a sentence. Observable.Reduce emits only the final aggregate, such as the total length of the words. Both methods allow the accumulator type to differ from the input type.

rx/examples/pipeline/main.go
// Scan emits every intermediate result, Reduce only the final one. Both
// are generic methods, so the result type may differ from the input.
words := rx.Just("go", "is", "fun")
sentence, _ := words.Scan("", func(acc, w string) string {
	if acc == "" {
		return w
	}
	return acc + " " + w
}).Collect(ctx)
totalLen, _ := words.Reduce(0, func(sum int, w string) int { return sum + len(w) }).Collect(ctx)
View on GitHub

Consume results

Use Observable.All to decide inside a loop when to stop. Iterate with range to receive each value and error. Exiting the loop early stops the source.

rx/examples/pipeline/main.go
// All hands the results to a range loop, like iterating over a slice.
for label, err := range rx.Range(1, 3).Map(strconv.Itoa).All(ctx) {
	if err != nil {
		fmt.Println("error:", err)
		break
	}
	fmt.Println("received #" + label)
}
View on GitHub

Use Observable.Subscribe and Observer to handle events with callbacks. Supply the callbacks you need and wait for the subscription to finish with Subscription.Done.

rx/examples/pipeline/main.go
// Subscribe delivers events to the callbacks of an Observer; leave out
// the callbacks you do not need.
sub := rx.Just(1, 2).Subscribe(ctx, rx.Observer[int]{
	Next:     func(n int) { fmt.Println("value", n) },
	Complete: func() { fmt.Println("done") },
})
<-sub.Done()
View on GitHub

On this page