AHFuture 0.1.8

AHFuture 0.1.8

测试已测试
语言语言 SwiftSwift
许可 MIT
发布上次发布2019年5月
SPM支持 SPM

Alex HmelevskiAlex HmelevskiPiyush Sharma 维护。



AHFuture 0.1.8

  • AlexHmelevski

AHFuture

CI Status Version License Platform

AHFuture 是使用 futures 构想异步 API 的概念。

AHFuture 在 Swift 中实现了经过验证的函数式概念,为 completion blocks 提供了强大的替代方案,并支持在异步代码中进行安全的错误处理。

示例

我们编写大量的异步代码。无论是等待从网络获取的数据,还是希望在主线程上执行一个昂贵的计算并在更新 UI 后完成,我们经常进行 '触发和回调' 舞蹈。以下是一个典型的异步代码片段

User.logIn(username, password) { user, error in
    if !error {
        Posts.fetchPosts(user, success: { posts in
            // do something with the user's posts
        }, failure: handleError)
    } else {
        handleError(error) // handeError is a custom function to handle errors
    }
}

现在让我们看看 AHFuture 能为您做什么

User.logIn(username, password).flatMap { user in
    Posts.fetchPosts(user)
}.onSuccess { posts in
    // do something with the user's posts
}.onFailure { error in
    // either logging in or fetching posts failed
}.execute()

支持的操作

map

如果成功,将把User响应转换为可以用于成功块的UserViewModel

User.logIn(username, password).map { UserViewModel.init }
.onSuccess { viewModel in
    // do something with viewModel
}.onFailure { error in
    // either logging in or fetching posts failed
}.execute()

flatMap

如果登录成功,则响应将被转换为另一个AHFuture,成功块将包含来自第二个AHFuture的结果。

User.logIn(username, password).flatMap { Posts.fetchPosts }
.onSuccess { posts in
    // do something with the user's posts
}.onFailure { error in
    // either logging in or fetching posts failed
}.execute()

filter

如果谓词为真,将执行完成。

User.logIn(username, password).flatMap { Posts.fetchPosts }
			      .filter { PostFilter.isTodaysPost }
.onSuccess { posts in
    // do something with the user's posts
}.onFailure { error in
    // either logging in or fetching posts failed
}.execute()

retry

重试算子会在出错时尝试执行AHFuture。参数表示尝试次数。

User.logIn(username, password).flatMap { Posts.fetchPosts }
			      .retry(5)
.onSuccess { posts in
    // do something with the user's posts
}.onFailure { error in
    // either logging in or fetching posts failed
}.execute()

recover

恢复算子帮助将错误转换为占位符对象。

User.logIn(username, password).flatMap { Posts.fetchPosts }
			      .retry(5)
                              .recover {ErrorHandler.transformToPlaceholderModel}
.onSuccess { posts in
    // do something with the user's posts
}.onFailure { error in
    // either logging in or fetching posts failed
}.execute()

run/observe

有时我们需要在特定的线程上运行我们的工作,并在另一个线程上进行观察。为此,有一个run算子。

Calculator.primeNumber(number)
.run(on: myGlobalQueue)
.observe(on: .main)
.onSuccess { posts in
    // do something with the user's posts
}.onFailure { error in
    // either logging in or fetching posts failed
}.execute()

安装

AHFuture 可通过 CocoaPods 获取。要安装它,只需将以下行添加到您的 Podfile 文件中

pod "AHFuture"

待办

  • 添加超时操作符
  • 添加同步、连接/拼接、序列压缩操作符

作者

Alex Hmelevski,[email protected]

许可

AHFuture 在 MIT 许可下可用。有关更多信息,请参阅 LICENSE 文件。