Combine 系列

目的: 使用断点、打印、记录语句或其他额外的逻辑,以便更有针对性地了解管道内发生的情况。
handleEvents 传入数据,不对输出和失败类型或数据进行任何修改。 当你在管道中加入该操作符时,可以指定一些可选的闭包,从而让你能够专注于你想要看到的信息。 具有特定闭包的 handleEvents 操作符是一个打开新窗口的好方法,通过该窗口可以查看管道取消、出错或以其他预期的方式终止时发生的情况。
可以指定的闭包包括:
receiveSubscriptionreceiveRequestreceiveCancelreceiveOutputreceiveCompletion如果每个闭包都包含打印语句,则该操作符将非常像 print 操作符,具体表现在 使用 print 操作符调试管道。
使用 handleEvents 调试的强大之处在于可以选择要查看的内容、减少输出量或操作数据以更好地了解它。
在 UIKit-Combine/GithubViewController.swift 的示例 viewcontroller 中,订阅、取消和 completion 的事件被用于启动或停止 UIActivityIndicatorView。
如果你只想看到管道上传递的数据,而不关心控制消息,那么为 receiveOutput 提供单个闭包并忽略其他闭包可以让你专注于这些详细信息。
handleEvents 的单元测试示例展示了所有可提供的闭包:
UsingCombineTests/HandleEventsPublisherTests.swift
.handleEvents(receiveSubscription: { aValue in
print("receiveSubscription event called with \(String(describing: aValue))") // 2
}, receiveOutput: { aValue in // 3
print("receiveOutput was invoked with \(String(describing: aValue))")
}, receiveCompletion: { aValue in // 4
print("receiveCompletion event called with \(String(describing: aValue))")
}, receiveCancel: { // 5
print("receiveCancel event invoked")
}, receiveRequest: { aValue in // 1
print("receiveRequest event called with \(String(describing: aValue))")
})
receiveRequest,所需要的值(the demand value)将传递给它。receiveSubscription 通常是从发布者返回的订阅消息,它将对订阅的引用传递给发布者。 此时,管道已运行,发布者将根据原始请求中请求的数据量提供数据。receiveOutput 中,每次有值传递过来都将调用该闭包。 这将随着发布者发送更多的值而重复调用。虽然你还可以使用 breakpoint 和 breakpointOnError 操作符进入调试模式(如使用调试器调试管道 中所示),带有闭包的 handleEvents() 操作符允许你在 Xcode 内设置断点。 这允许你立即进入调试器,检查流经管道的数据,或获取订阅者的引用,或在失败的 completion 事件中获取错误信息。
https://heckj.github.io/swiftui-notes/index_zh-CN.html
https://github.com/heckj/swiftui-notes