RxGo 的 DistinctUntilChanged 操作符:如何抑制流中的连续重复元素
RxGo 的 DistinctUntilChanged 操作符:如何抑制流中的连续重复元素
导读
DistinctUntilChanged 是 RxGo(Reactive Extensions for the Go language)提供的过滤类操作符,其核心语义是抑制原始 Observable 中连续重复的条目(Suppress consecutive duplicate items in the original Observable),仅当相邻元素的取值发生变化时才向下游发射。它特别适合去抖监控指标、过滤传感器重复读数、净化日志流等只关心"值是否发生变化"的场景。读完本文,你将掌握该操作符的签名与选择器函数(Func)用法、它与 Distinct 的本质区别、底层实现原理,以及它支持的全部可选参数(Options)及其在源码层面的作用。
一、操作符语义:DistinctUntilChanged 到底过滤什么
先看官方文档给出的最简定义与示例(doc/distinctuntilchanged.md):
observable := rxgo.Just(1, 2, 2, 1, 1, 3)().
DistinctUntilChanged(func(_ context.Context, i interface{}) (interface{}, error) {
return i, nil
})
上游依次发射 1, 2, 2, 1, 1, 3,经过 DistinctUntilChanged 后输出:
1
2
1
3
观察这个结果可以发现关键规律:第二个 2 因为与前一个元素 2 相同被抑制;第二个 1 同样因为与前一个元素相同被丢弃;而第一个 1(位于序列开头)和第二个 1 之前的那个 2 之间的 1,虽然与序列最开头的 1 值相等,但它们在时间上并不连续,因此仍然会通过。也就是说,该操作符只做"相邻去重",不做"全局去重"。
这一点在 README 中也被明确归类为去重类操作符(README.md):
Distinct/DistinctUntilChanged— suppress duplicate items emitted by an Observable
二、与 Distinct 的对比:相邻去重 vs 全局去重
要真正理解 DistinctUntilChanged,必须把它和同族的 Distinct 放在一起对比。两者的接口签名完全相同(均定义在 observable.go 的 Observable 接口中):
Distinct(apply Func, opts ...Option) Observable
DistinctUntilChanged(apply Func, opts ...Option) Observable
但从源码实现看,二者的内部状态截然不同(observable_operator.go):
Distinct内部维护一个keyset map[interface{}]interface{},记住历史上出现过的所有 key,只要某个 key 曾经出现过,后续再次出现就一律丢弃——这是"全局去重"。DistinctUntilChanged内部只维护一个current interface{}字段,仅记录最近一次通过的元素 key,只要当前 key 与上一个 key 不同就放行——这是"相邻去重"。
用同一组输入 1, 2, 2, 1, 1, 3 验证:
| 操作符 | 输出 | 差异点 |
|---|---|---|
Distinct |
1, 2, 3 |
序列中的第二个 1 因历史上出现过被丢弃 |
DistinctUntilChanged |
1, 2, 1, 3 |
序列中的第二个 1 因与前一个 2 不连续相同而被保留 |
因此,如果你的需求是"整条流中每个值只出现一次",请使用 Distinct;如果需求是"只在值发生跳变时通知下游"(例如监控告警中的状态翻转检测),DistinctUntilChanged 才是正确的选择,它的内存占用也恒定(只有 current 一个字段),不随流长度增长。
三、选择器函数 Func:提取用于比较的 key
DistinctUntilChanged 的第一个参数是 Func 类型,定义于 types.go:
Func func(context.Context, interface{}) (interface{}, error)
该函数接收 context.Context 和当前条目值,返回两样东西:
interface{}类型的 key:用于比较的值。你可以直接返回元素本身(如示例中的return i, nil),也可以返回元素的某个投影字段——例如从结构体中提取 ID、从日志中提取日志级别,从而"针对该维度判断相邻是否相同"。error:如果返回非 nil 错误,操作符会立即向下游发送错误并停止处理。
看一个"提取字段作为 key"的实战写法:
type sensorReading struct {
deviceID string
value float64
}
observable := rxgo.Just(
sensorReading{"A", 10.0},
sensorReading{"A", 10.0},
sensorReading{"B", 10.0},
)().DistinctUntilChanged(func(_ context.Context, i interface{}) (interface{}, error) {
return i.(sensorReading).deviceID, nil
})
此时比较的是 deviceID 字段,输出为第一条 A 记录与第一条 B 记录(第二条 A 记录因与第一条相邻且 deviceID 相同被抑制)——这展示了"对结构体流按指定维度做相邻去重"的典型用法。
四、源码级原理:distinctUntilChangedOperator 的执行流程
DistinctUntilChanged 的工厂方法实现在 observable_operator.go:
// DistinctUntilChanged suppresses consecutive duplicate items in the original Observable.
// Cannot be run in parallel.
func (o *ObservableImpl) DistinctUntilChanged(apply Func, opts ...Option) Observable {
return observable(o.parent, o, func() operator {
return &distinctUntilChangedOperator{
apply: apply,
}
}, true, false, opts...)
}
它通过内部 observable(...) 工厂(定义于 observable.go)包装出一个新的 Observable,forceSeq 参数传 true,从工厂函数的分支逻辑可以看出:无论是否配置了并行池,该操作符都会被强制以串行(顺序)方式执行——这与方法注释中的 "Cannot be run in parallel" 完全对应。
核心状态机是 distinctUntilChangedOperator(observable_operator.go):
type distinctUntilChangedOperator struct {
apply Func
current interface{}
}
func (op *distinctUntilChangedOperator) next(ctx context.Context, item Item, dst chan<- Item, operatorOptions operatorOptions) {
key, err := op.apply(ctx, item.V)
if err != nil {
Error(err).SendContext(ctx, dst)
operatorOptions.stop()
return
}
if op.current != key {
item.SendContext(ctx, dst)
op.current = key
}
}
next 的处理逻辑可以归纳为三步:
- 计算 key:对
item.V调用apply选择器,得到用于比较的 key;若返回错误,则通过Error(err).SendContext(ctx, dst)向输出通道发送错误条目,并调用operatorOptions.stop()终止处理(配合默认的StopOnError策略)。 - 相邻比较:判断
op.current != key。注意这里比较的是interface{}的相等性,即 Go 的可比较类型(整型、字符串、指针等)直接比较;对于切片、map 等不可比较类型,需要你在Func中自行转换为可比较的 key(如字符串或哈希值)。 - 放行或抑制:若 key 与上一个通过的 key 不同,则把原始条目(不是 key)通过
item.SendContext(ctx, dst)发送给下游,并更新op.current;若相同则直接丢弃。
值得注意的是:操作符更新的是 current 这个"最近通过"的值,而不是"最近见过"的值。由于第二个 1(与开头的 1 相同)出现在 2 之后,此时 op.current == 2,与 1 不同,所以它会被放行——这正是第一节示例输出 1, 2, 1, 3 的底层原因。
此外,err 方法委托给 defaultErrorFuncOperator 做默认错误转发,end 与 gatherNext 为空实现,说明该操作符不参与并行 gather 阶段,进一步印证了它的串行本质。
五、Options 详解:DistinctUntilChanged 支持的五个可选参数
与原文档一致,DistinctUntilChanged 接受的可选参数(opts ...Option)包括以下五种,完整说明见 doc/options.md。
1. WithBufferedChannel
配置输出通道的缓冲容量,影响背压行为:
observable := rxgo.Just(1, 2, 2, 1, 3)().
DistinctUntilChanged(func(_ context.Context, i interface{}) (interface{}, error) {
return i, nil
}, rxgo.WithBufferedChannel(1)) // 创建容量为 1 的缓冲通道
其实现(options.go)会设置 isBuffer = true 与 buffer = capacity,供内部 buildChannel 创建相应容量的通道。
2. WithContext
允许传入一个 context.Context,Observable 会监听其 done 信号来关闭自身,用于实现超时取消与优雅退出:
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
observable := rxgo.Just(1, 2, 2, 1, 3)().
DistinctUntilChanged(func(_ context.Context, i interface{}) (interface{}, error) {
return i, nil
}, rxgo.WithContext(ctx))
从 options.go 的 buildContext 可以看到,如果同时传入父级 context,会通过 onecontext.Merge 将二者合并;否则回退到传入的 ctx、父级 context 或 context.Background()。
3. WithObservationStrategy
指定观测(消费)策略(options.go):
rxgo.Lazy(默认):只有当 Observer 开始订阅时才消费数据;rxgo.Eager:Observable 一创建即开始消费:
observable := rxgo.Just(1, 2, 2, 1, 3)().
DistinctUntilChanged(func(_ context.Context, i interface{}) (interface{}, error) {
return i, nil
}, rxgo.WithObservationStrategy(rxgo.Eager))
4. WithErrorStrategy
指定错误处理策略(options.go):
rxgo.StopOnError(默认):Observable 产生错误时停止处理;rxgo.ContinueOnError:Observable 产生错误时继续处理后续条目。
observable := rxgo.Just(1, 2, 2, 1, 3)().
DistinctUntilChanged(func(_ context.Context, i interface{}) (interface{}, error) {
return i, nil
}, rxgo.WithErrorStrategy(rxgo.ContinueOnError))
该策略会被传播到其父级 Observable。值得注意的是,在 next 的实现中,当 apply 返回错误时调用了 operatorOptions.stop(),因此即使配置 ContinueOnError,选择器函数自身产生的错误也会触发终止,二者需要结合使用场景仔细权衡。
5. WithPublishStrategy
创建一个可连接的 Observable(Connectable Observable),数据只有在调用 Connect(ctx) 后才开始发射,用于多订阅者共享同一份数据流:
observable := rxgo.Just(1, 2, 2, 1, 3)().
DistinctUntilChanged(func(_ context.Context, i interface{}) (interface{}, error) {
return i, nil
}, rxgo.WithPublishStrategy())
该选项同样会传播到父级 Observable(详见 doc/options.md)。
六、串行执行的边界:传入并行池选项会怎样
虽然第四节已经说明该操作符内部以 forceSeq=true 强制串行,但仓库测试中专门存在一个并行场景用例 Test_Observable_DistinctUntilChanged_Parallel(observable_operator_test.go):
func Test_Observable_DistinctUntilChanged_Parallel(t *testing.T) {
defer goleak.VerifyNone(t)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
obs := testObservable(ctx, 1, 2, 2, 1, 3).DistinctUntilChanged(func(_ context.Context, item interface{}) (interface{}, error) {
return item, nil
}, WithCPUPool())
Assert(ctx, t, obs, HasItems(1, 2, 1, 3))
}
这个测试用例说明:即使传入 WithCPUPool()(将操作符声明为并行、并发 goroutine 数为 runtime.NumCPU(),见 doc/options.md),由于 DistinctUntilChanged 的 forceSeq 为 true,在 observable 工厂的 if forceSeq || !parallel 分支中仍然走 runSequential 串行执行路径,输出结果与串行场景完全一致。因此在实际工程中,为它配置 WithPool(n) / WithCPUPool() 并不会带来并行收益,也不会破坏相邻去重的语义正确性。
七、测试验证与快速运行
仓库提供了完整的单元测试用例(observable_operator_test.go):
func Test_Observable_DistinctUntilChanged(t *testing.T) {
defer goleak.VerifyNone(t)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
obs := testObservable(ctx, 1, 2, 2, 1, 3).DistinctUntilChanged(func(_ context.Context, item interface{}) (interface{}, error) {
return item, nil
})
Assert(ctx, t, obs, HasItems(1, 2, 1, 3))
}
测试断言输出为 1, 2, 1, 3,与原文档示例一致,可作为行为规范的权威依据。同时,两个测试用例都调用了 goleak.VerifyNone(t) 来校验没有 goroutine 泄漏,说明该操作符在正常终止后会正确关闭内部通道。
可以在仓库根目录直接运行该测试进行验证:
go test -run Test_Observable_DistinctUntilChanged -v .
(项目以 github.com/reactivex/rxgo/v2 为 module 名、go 1.13 为最低版本要求,见 go.mod。)
八、小结
DistinctUntilChanged 是 RxGo 中一个"小而专"的过滤操作符:它以 Func 选择器提取 key,仅抑制相邻连续重复的元素,内存占用恒定,且无论是否配置并行池都被强制串行执行,保证语义确定性。它与全局去重的 Distinct 各司其职,选择时只需回答一个问题:你要过滤的是"历史上出现过的"还是"刚刚出现过的"重复。
相关参考: