luminyra

Quickstart

Build a number stream, filter and transform it, take the first few values, and collect the results.

Run the stream example

Use Go 1.27 or later. Install rx, save the complete example as main.go, and run go run .. From the rx source directory, run go run ./examples/pipeline.

go get github.com/luminyra/rx
Complete number stream example
// Command pipeline builds rx pipelines by chaining operator methods and
// consumes them with Collect, All and Subscribe.
package main

import (
	"context"
	"fmt"
	"strconv"

	"github.com/luminyra/rx"
)

func main() {
	ctx := context.Background()

	// 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)
	fmt.Println(values, err)

	// 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)
	fmt.Printf("%q\n", sentence)
	fmt.Println(totalLen)

	// 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)
	}

	// 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

Follow the order of operations

Start with Range, use Observable.Filter to find multiples of three, transform those with Observable.Map, then limit the count with Observable.Take. The test below collects the transformed values into a slice of labels.

rx/example_test.go
labels := rx.Range(1, 20).
	Filter(func(n int) bool { return n%3 == 0 }).
	Map(func(n int) string { return "#" + strconv.Itoa(n) }).
	Take(3)

values, err := labels.Collect(context.Background())
fmt.Println(values, err)
Expected output
[#3 #6 #9] <nil>
View on GitHub

Read about consuming results next.

On this page