使用指南
操作符与消费方式
按顺序组合操作符,比较累积和聚合,并用迭代器或回调读取结果。
组合操作符
示例从 Range 生成数值,依次筛选 3 的倍数、求平方、限量,最后用 Observable.Collect 收集。管线按方法顺序处理,每次转换的结果是下一步输入。
// 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)比较中间结果和最终结果
Observable.Scan 送出每次累积后的结果,例如逐步拼出的句子。Observable.Reduce 只送出最终聚合值,例如全部词语的长度总和。两个方法都允许累积值与输入的类型不同。
// 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)消费结果
希望在循环内决定何时停止时,使用 Observable.All。用 range 接收每个值和错误,提前退出循环会停止数据源。
// 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)
}希望用回调处理事件时,使用 Observable.Subscribe 和 Observer。只提供需要的回调,使用 Subscription.Done 等待订阅结束。
// 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()