- 目的
-
-
使用断点、打印、记录语句或其他额外的逻辑,以便更有针对性地了解管道内发生的情况。
-
- 参考
-
-
使用 handleEvents 的 ViewController 在 github 项目中位于 UIKit-Combine/GithubViewController.swift
-
有关 handleEvents 的单元测试在 github 项目中位于 UsingCombineTests/HandleEventsPublisherTests.swift
- 另请参阅
- 代码和解释
-
handleEvents 传入数据,不对输出和失败类型或数据进行任何修改。 当你在管道中加入该操作符时,可以指定一些可选的闭包,从而让你能够专注于你想要看到的信息。 具有特定闭包的 handleEvents 操作符是一个打开新窗口的好方法,通过该窗口可以查看管道取消、出错或以其他预期的方式终止时发生的情况。
可以指定的闭包包括:
-
receiveSubscription
-
receiveRequest
-
receiveCancel
-
receiveOutput
-
receiveCompletion
如果每个闭包都包含打印语句,则该操作符将非常像 print 操作符,具体表现在 patterns.adoc。
使用 handleEvents 调试的强大之处在于可以选择要查看的内容、减少输出量或操作数据以更好地了解它。
在 UIKit-Combine/GithubViewController.swift 的示例 viewcontroller 中,订阅、取消和 completion 的事件被用于启动或停止 UIActivityIndicatorView。
如果你只想看到管道上传递的数据,而不关心控制消息,那么为 receiveOutput
提供单个闭包并忽略其他闭包可以让你专注于这些详细信息。
handleEvents 的单元测试示例展示了所有可提供的闭包:
.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
中,每次有值传递过来都将调用该闭包。 这将随着发布者发送更多的值而重复调用。 -
如果管道正常关闭或因失败而终止,
receiveCompletion
闭包将收到 completion 事件。 就像 sink 闭包一样,你可以对提供的 completion 事件使用 switch,如果它是一个.failure
completion,那么你可以检查附带的错误。 -
如果管道被取消,则将调用
receiveCancel
闭包。 不会有任何数据传递到该取消闭包中。
Note
|
虽然你还可以使用 reference.adoc 和 reference.adoc 操作符进入调试模式(如patterns.adoc 中所示),带有闭包的 |