快速上手
构造数值流,筛选、转换再截取前几项,收集实际结果。
运行流处理示例
使用 Go 1.27 或更高版本,安装 rx 后把完整示例保存到 main.go,运行 go run .。在 rx 源码目录也可执行 go run ./examples/pipeline。
go get github.com/luminyra/rx// 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()
}阅读处理顺序
从 Range 开始,用 Observable.Filter 找出 3 的倍数,用 Observable.Map 转换这些值,再用 Observable.Take 限制数量。以下测试把转换结果收集为标签切片。
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)[#3 #6 #9] <nil>接着看 流的消费方式。