SwiftUI Combine Framework 共享receiveCompletion 代码块
Posted
技术标签:
【中文标题】SwiftUI Combine Framework 共享receiveCompletion 代码块【英文标题】:SwiftUI Combine Framework shared receiveCompletion code block 【发布时间】:2021-06-29 13:48:58 【问题描述】:在 SwiftUI 订阅者中,您通常会拥有这个
authenticate
.receive(on: DispatchQueue.main) // Move to the main thread
.sink(receiveCompletion: completion in
switch completion
case .failure(let error): ()
case .finished: ()
, receiveValue: _ in )
我想提取要在多个订阅者之间共享的 receiveCompletion 代码块,期望相同的完成,即下面要分开并在多个订阅者中使用。
receiveCompletion: completion in
switch completion
case .failure(let error): ()
case .finished: ()
【问题讨论】:
您可以简单地为“receiveCompletion”创建一个单独的函数并将该函数传递到任何地方。 @andykkt,我似乎做得不对。然而,要正确地将我的手包裹在封闭物周围。请帮忙 一个(可能很有趣)旁注:如果错误的类型是Never
,您可以省略receiveCompletion
部分(以防您只对接收新值感兴趣)。您可以通过将错误映射到某个值来实现这一点(可能是nil
)
【参考方案1】:
你可以只写简单的函数来封装逻辑:
extension Publisher where Failure == Never
public func sinkOnMain(
receiveValue: @escaping ((Self.Output) -> Void)) -> AnyCancellable
receive(on: RunLoop.main)
.sink(receiveValue: receiveValue)
extension Publisher
public func sinkOnMain(
receiveCompletion: @escaping ((Subscribers.Completion<Self.Failure>) -> Void),
receiveValue: @escaping ((Self.Output) -> Void)) -> AnyCancellable
receive(on: RunLoop.main)
.sink(receiveCompletion: receiveCompletion, receiveValue: receiveValue)
它们都与普通的sink
做同样的工作,但首先将执行移至主运行循环。
【讨论】:
【参考方案2】:这就是我要找的东西
static func handleCompletion(completion: Subscribers.Completion<Error>)
switch completion
case .failure(let error): ()
case .finished: ()
那就这样称呼吧
authenticate
.receive(on: DispatchQueue.main) // Move to the main thread
.sink(receiveCompletion: handleCompletion
, receiveValue: _ in )
【讨论】:
以上是关于SwiftUI Combine Framework 共享receiveCompletion 代码块的主要内容,如果未能解决你的问题,请参考以下文章
swiftui+combine:为啥滚动 LazyVGrid 时 isFavoriteO 改变了?
使用 Combine 和 SwiftUI 显示变化值的最简洁方式是啥?