(WWDC) 初探 Combine

2019-06-19  本文已影响0人  FicowShen

内容概览




前言

假设你需要构建如下应用:

App要求:

你会如何实现?实现的过程会应用到哪些概念?



你需要使用 Target/Action 来获取输入框的最新值,使用计时器来实现定期检查,使用 KVO 来控制加载指示器的状态。

你还需要使用 URLSession 来进行网络请求,汇总三个输入框的结果,然后通过 KVC 来控制按钮的可用状态。



涉及到的异步接口:



是否觉得,这些步骤略显繁琐?
是否有更好的解决方案呢?




Combine

Combine 提供了统一的、声明式的API,可以随着时间的推移处理多个值



Combine 特性:



核心概念:




Publisher

protocol Publisher {

    associatedtype Output
    associatedtype Failure: Error
    
    func subscribe<S: Subscriber>(_ subscriber: S)
      where S.Input == Output, S.Failure == Failure
}

为 Publisher 拓展通知中心

extension NotificationCenter {
    struct Publisher: Combine.Publisher {
        typealias Output = Notification
        typealias Failure = Never
        init(center: NotificationCenter, name: Notification.Name, object: Any? = nil)
    }
}




Subscribers

protocol Subscriber {

    associatedtype Input
    associatedtype Failure: Error
    
    func receive(subscription: Subscription)
    func receive(_ input: Input) -> Subscribers.Demand
    func receive(completion: Subscribers.Completion<Failure>)
}
extension Subscribers {

    class Assign<Root, Input>: Subscriber, Cancellable {
        typealias Failure = Never
    }
    
    init(object: Root, keyPath: ReferenceWritableKeyPath<Root, Input>)
}



Publisher 和 Subscriber 之间的关系

  1. Subscriber 被绑定到 Publisher 上
  2. Publisher 发送一个订阅
  3. Subscriber 向 Publisher 请求值
  4. Publisher 向 Subscriber 发送值
  5. Publisher 发送完成事件



使用 Publisher 和 Subscriber 的示例代码:

class Wizard {
    var grade: Int
}

let merlin = Wizard(grade: 5)

let graduationPublisher = NotificationCenter.Publisher(center: .default, name: .graduated, object: merlin)
let gradeSubscriber = Subscribers.Assign(object: merlin, keyPath: \.grade)

graduationPublisher.subscribe(gradeSubscriber)

以上代码由于类型不匹配,会遭遇如下错误:



看来,我们需要通过某种方式来实现类型匹配。




Operators

extension Publishers {
    struct Map<Upstream: Publisher, Output>: Publisher {
        typealias Failure = Upstream.Failure
        
        let upstream: Upstream
        let transform: (Upstream.Output) -> Output
    } 
}



现在,我们可以通过优雅的方式解决之前的问题。

let graduationPublisher = NotificationCenter.Publisher(center: .default, name: .graduated, object: merlin)
let gradeSubscriber = Subscribers.Assign(object: merlin, keyPath: \.grade)

let converter = Publishers.Map(upstream: graduationPublisher) { note in
    return note.userInfo?["NewGrade"] as? Int ?? 0
}

converter.subscribe(gradeSubscriber)

使用 Map Operator,我们完成了订阅操作。

不过,还可以把步骤简化一下:

extension Publisher {
    func map<T>(_ transform: @escaping (Output) -> T) -> Publishers.Map<Self, T> {
        return Publishers.Map(upstream: self, transform: transform)
    }
}

let cancellable = NotificationCenter.default.publisher(for: .graduated, object: merlin)
                    .map { note in
                        return note.userInfo?["NewGrade"] as? Int ?? 0
                    }
                    .assign(to: \.grade, on: merlin)

声明式 Operator API 的优点:



在使用 Operator 时,优先尝试进行组合

在对单个值(如:独立的网络请求)进行异步操作时,推荐使用 Future
在对多个值(如:帐号密码输入框的事件流)进行异步操作时,推荐使用 Publisher



使用 map 的部分其实还可以优化

使用 compactMap 简化操作:

进行筛选:

截取部分值:



还可以组合多个 Publisher:


使用建议

更多内容

欢迎继续阅读 (WWDC) 实践 Combine




参考内容:
Introducing Combine




转载请注明出处,谢谢~

上一篇 下一篇

猜你喜欢

热点阅读