【问题标题】:SwiftUI Combine Framework shared receiveCompletion code blockSwiftUI Combine Framework 共享receiveCompletion 代码块
【发布时间】: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

标签: ios swift swiftui combine


【解决方案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 })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-17
      • 1970-01-01
      • 2018-08-27
      • 2010-11-12
      • 2021-09-12
      • 1970-01-01
      • 1970-01-01
      • 2017-12-01
      相关资源
      最近更新 更多