CI

操作 (Action)

这个库与 RxSwift 一起使用,以在 Observables 之上提供一个抽象层:Actions。

Action 是一种表示 “嘿,稍后我需要你订阅这个东西” 的方式。 实际上它比这更复杂。

Actions 接受一个 workFactory:一个闭包,它接收一些输入并产生一个 observable。 当在 action 上调用 execute() 时,workFactory 会接收到这个参数,并且 action 会订阅返回的 observable。

一个 Action

哦,它还有一个非常 Swift 的特性,与 UIButton 结合起来非常酷。 它会管理按钮的 enabled 状态,确保在你的工作完成时按钮被禁用,所有这些 👍

用法

您必须传递一个接收输入并返回 ObservableworkFactory。 这代表需要完成的某些工作。 每当您调用 execute() 时,您传入的输入会被传递给 work factory。 Action 将订阅该 observable 并在其 elements 属性上发出 Next 事件。 如果 observable 发生错误,该错误将作为 Next 事件发送到 errors 属性。 很棒。

Actions 一次只能执行一个操作。 如果您尝试执行当前正在执行的 action,您将收到一个错误。 executing 属性发送 truefalse 值作为 Next 事件。

action: Action<String, Bool> = Action(workFactory: { input in
    return networkLibrary.checkEmailExists(input)
})

...

action.execute("ash@ashfurrow.com")

请注意,第一个泛型参数是输入的类型,第二个是 workFactory 创建的 observable 的类型。 您可以将它看作是 action 的“输出”。

您还可以为 Action 初始化器指定一个 enabledIf 参数。

let validEmailAddress = emailTextField.rx.text.map(isValidEmail)

action: Action<String, Bool> = Action(enabledIf: validEmailAddress, workFactory: { input in
    return networkLibrary.checkEmailExists(input)
})

现在,只有当电子邮件地址有效时,execute() 才会执行工作。 超级酷!

(请注意,enabledIfenabled 属性不同。 您传入 enabledIf,并且 action 使用它(与其当前执行状态相结合)来确定它当前是否启用。)

真正 酷的是 UIButton 扩展。 它接受一个 CocoaAction,它只是 Action<Void, Void>

button.rx.action = action

现在,当按下按钮时,该 action 会被执行。 按钮的 enabled 状态绑定到 action 的 enabled 属性。 这意味着您可以将表单验证逻辑作为信号输入到 action 中,并且您的按钮的 enabled 状态会为您处理。 此外,由于它一次只处理一件事情,因此用户在 action 完成执行之前无法再次按下该按钮。 很酷。 请查看 CocoaAction action 中的代码示例

如果您想使用 Action 来执行复杂的操作,例如文件下载并报告下载进度(例如,更新 UI 中的进度条),您应该使用 Action<Void, Int> 而不是 CocoaAction。 开箱即用的 CocoaAction 无法发出进度值,您自己的 Action<Void, Int> 可以做到这一点。 有关详细信息,请参阅 这篇文章

如果您的场景涉及许多需要触发相同 Action 的按钮,并提供不同的输入,您可以使用每个 UIButton 上的 bindTo 和一个返回正确输入的闭包。

let button1 = UIButton()
let button2 = UIButton()

let action = Action<String, String> { input in
    print(input)
    return .just(input)
}
button1.rx.bindTo(action) { _ in return "Hello"}
button2.rx.bindTo(action) { _ in return "Goodbye"}

button1button2 共享同一个 Action,但它们使用不同的输入来喂给它(HelloGoodbye 将为相应的点击打印)。

一个更复杂的用例是与管理导航、错误处理和加载状态的 UIViewController 相关的单个 action。 通过这种方法,您可以拥有任意数量的 UIButton(或 UIBarButtonItem),并且可以一次性地在单个公共位置订阅 executingerrorselementscompletions

UIAlertAction 上还有一个非常酷的扩展,被 UIAlertController 使用。 一个注意事项:由于该类的限制,您不能使用正常的初始化器来实例化它。 而是调用这个类方法

let action = UIAlertAction.Action("Hi", style: .default)

安装

CocoaPods

只需将以下行添加到您的 Podfile 中

pod 'Action'

然后运行 pod install,一切都会 👌

Carthage

将此添加到 Cartfile

github "RxSwiftCommunity/Action" ~> 5.0.0

如果您使用的是 RxSwift 3.2.0 或更低版本,请改用 Action ~2.2.0

然后运行

> carthage update

感谢

这个库(很明显)受到 ReactiveCocoaAction 的启发。 那些开发者值得感谢!

许可

MIT 协议 (obvs.)

Permissive licenses are the only licenses permitted in the Q continuum.