多订阅者订阅上游时自定义Combine Publisher异常排查
自定义Combine Publisher多订阅时的行为异常排查与解决
问题背景
自定义了CollectOnReceive Publisher,需求是:当上游出现第一个>=4的值后,收集后续5秒内的所有值,替代固定间隔的collect(.byTime)。但当同时存在两个订阅者(一个通过自定义Publisher订阅,一个直接用sink订阅)时,出现值被分流的异常:偶数值流向普通sink,奇数值流向自定义Publisher。
异常现象
日志输出如下:
-- observing -- sending 1 sending 2 sending 3 sending 4 c2 sink: 4 sending 5 -- appending: 5 sending 6 start: 2022-09-08 22:45:54 +0000 sending 7 -- appending: 7 sending 8 c2 sink: 8. // missing the append for all the even values!!! sending 9 -- appending: 9 sending 10 c2 sink: 10 sending 11 -- appending: 11 sending 12 c2 sink: 12 sending 13 -- appending: 13 sending 14 c2 sink: 14 sending 15 -- appending: 15 sending 16 c2 sink: 16 --finish sub: [5, 7, 9, 11, 13, 15] : 2022-09-08 22:45:59 +0000 values: [5, 7, 9, 11, 13, 15]
原因分析
- 冷Publisher的多订阅问题:上游
pub是冷Publisher(Timer.publish默认是冷的),每个订阅都会触发上游从头执行。加上自定义CollectOnReceive的Subscription中对上游发起了两次独立订阅(一次收集值、一次取第一个值),再加上外部的sink订阅,总共存在3个独立的上游流。 - 全局变量的副作用:
map中使用了全局变量iter,每个流的map闭包都会递增iter,导致每个Timer事件生成3个连续数值,分别被3个订阅者接收,看起来像是奇偶分流。 - 自定义Publisher实现缺陷:在
request方法中重复订阅上游,没有复用同一个流的事件,导致逻辑混乱。
修复方案
1. 将上游转换为热Publisher
使用share()操作符让所有订阅共享同一个上游流,避免多次触发map中的副作用。
2. 重构自定义CollectOnReceive实现
只订阅上游一次,在同一个流中同时处理值收集和计时逻辑:
- 订阅上游后,立即收集所有值到缓冲区
- 监听第一个值的到来,启动5秒计时器
- 计时器触发后,发送缓冲区的所有值并完成订阅
最终实现代码
import UIKit import Foundation import Combine var iter = 0 // 使用share()将冷Publisher转为热Publisher,共享同一个流 var pub: AnyPublisher<Int, Never> = Timer.publish(every: 1, on: .main, in: .common) .autoconnect() .map { _ -> Int in iter += 1 print("sending \(iter)") return iter } .share() // 关键:共享流,避免多订阅重复执行map .eraseToAnyPublisher() /// Collects values and starts a timer after the `first` value from upstream is received. public struct CollectOnReceive<T: Publisher>: Publisher where T.Failure == Never { public typealias Output = [T.Output] public typealias Failure = T.Failure class Subscription<SubscriberType: Subscriber>: Combine.Subscription where SubscriberType.Input == Output, SubscriberType.Failure == Failure { private var cancellables: Set<AnyCancellable> = [] private let subscriber: SubscriberType private let upstream: T private let queue: DispatchQueue private var collection: Output = [] private var isTimerStarted = false init(upstream: T, subscriber: SubscriberType, queue: DispatchQueue) { self.subscriber = subscriber self.upstream = upstream self.queue = queue } func request(_ demand: Subscribers.Demand) { guard demand > .none else { return } upstream .receive(on: queue) .sink(receiveCompletion: { [weak self] completion in // 上游完成时,也发送当前收集的值 if let collection = self?.collection { _ = self?.subscriber.receive(collection) } self?.subscriber.receive(completion: completion) }, receiveValue: { [weak self] value in guard let self = self else { return } self.collection.append(value) // 仅在第一个值到来时启动计时器 guard !self.isTimerStarted else { return } self.isTimerStarted = true print("start: \(Date())") Timer.publish(every: 5, on: .main, in: .common) .autoconnect() .first() // 只取第一个计时事件 .receive(on: self.queue) .sink(receiveValue: { [weak self] _ in guard let self = self else { return } print("--finish sub: \(self.collection) : \(Date())") _ = self.subscriber.receive(self.collection) self.subscriber.receive(completion: .finished) self.cancellables.removeAll() }) .store(in: &self.cancellables) }) .store(in: &cancellables) } func cancel() { cancellables.removeAll() } } private let upstream: T private let queue: DispatchQueue public init(upstream: T, queue: DispatchQueue) { self.upstream = upstream self.queue = queue } public func receive<S>(subscriber: S) where S : Subscriber, T.Failure == S.Failure, [T.Output] == S.Input { subscriber.receive( subscription: Subscription( upstream: upstream, subscriber: subscriber, queue: queue ) ) } } extension Publisher where Failure == Never { func collectOnReceive(queue: DispatchQueue = .init(label: "CollectOnReceive")) -> CollectOnReceive<Self> { CollectOnReceive(upstream: self, queue: queue) } } let onlyGreaterThan4 = pub.drop(while: { value in return value < 4 }) let cancel = onlyGreaterThan4.collectOnReceive(queue: DispatchQueue(label: "collect on receive")).sink { print("completion: \($0)") } receiveValue: { print("values: \($0)") } let c2 = onlyGreaterThan4.sink { print("c2 sink: \($0)") }
修复后效果
- 所有订阅共享同一个上游流,
map中的iter每个Timer事件只递增一次 - 自定义Publisher会在第一个>=4的值(即4)到来时启动计时器,收集5秒内的所有值(4、5、6、7、8、9)
- 普通
sink会接收所有>=4的值,不会出现分流现象
内容的提问来源于stack exchange,提问作者Yogurt
相关产品推荐
相关产品推荐

