考虑以下代码:
CurrentValueSubject<Void, Error>(())
.eraseToAnyPublisher()
.sink { completion in
switch completion {
case .failure(let error):
print(error)
print("FAILURE")
case .finished:
print("SUCCESS")
}
} receiveValue: { value in
// this should be ignored
}
只要看看CurrentValueSubject
初始化程序,很明显该值不需要/无关紧要。
我正在使用这个特定的发布者发出异步网络请求,该请求可能会通过也可能会失败。
由于我对此发布者返回的值不感兴趣(没有),我怎样才能摆脱receiveValue
关闭?
理想情况下,调用站点代码应如下所示:
CurrentValueSubject<Void, Error>(())
.eraseToAnyPublisher()
.sink { completion in
switch completion {
case .failure(let error):
print(error)
print("FAILURE")
case .finished:
print("SUCCESS ")
}
}
也可能是我应该使用除AnyPublisher
,所以如果 API 更符合目的,请随意提出/重写。
我能找到的最接近的解决方案是忽略输出 https://developer.apple.com/documentation/combine/publisher/ignoreoutput(),但它仍然返回一个值。
您只需完成即可声明另一个接收器:
extension CurrentValueSubject where Output == Void {
func sink(receiveCompletion: @escaping ((Subscribers.Completion<Failure>) -> Void)) -> AnyCancellable {
sink(receiveCompletion: receiveCompletion, receiveValue: {})
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)