美文网首页
Combine -- 订阅与绑定

Combine -- 订阅与绑定

作者: jancywen | 来源:发表于2021-02-23 10:19 被阅读0次
发布-订阅

订阅

通过 sink 订阅 Publisher 事件

public func sink(
    receiveCompletion: @escaping ((Subscribers.Completion<Self.Failure>) -> Void),
    receiveValue: @escaping ((Self.Output) -> Void)
) -> AnyCancellable

sink 接受两个参数,它们都是 “闭包回调”:receiveCompletion 在 Self (也就是调用sink 的 Publisher) 发布结束事件时被调用,receiveValue 则在 Self 发布值时被调用。

绑定

Subscribers.Assign,它可以用来将 Publisher 的输出值通过 key path 绑定到一个对象的属性上去。

class Clock {
    var timeString: String = "" {
        didSet {print("\(timeString)")}
    }
}

let clock = Clock()

let formatter = DateFormatter()
formatter.timeStyle = .medium

let timer = Timer.publish(every: 1, on: .main, in: .default)
var token = timer.map{formatter.string(from:$0)}.assign(to: \.timeString, on: clock)
timer.connect()

DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
    token.cancel()
}
// 4:17:58 PM
// 4:17:59 PM
// 4:18:00 PM
// 4:18:01 PM
// 4:18:02 PM

分享

对于多个 Subscriber 对应一个 Publisher 的情况,如果我们不想让订阅行为反复发生 (比如上例中订阅时会发生网络请求),而是想要共享这个 Publisher 的话,使用 share() 将它转变为引用类型的 class。

相关文章

网友评论

      本文标题:Combine -- 订阅与绑定

      本文链接:https://www.haomeiwen.com/subject/dihkfltx.html